Get attributes and values from an XML file in Java

Suppose you want to get the attributes and values of the fuga tag from an xml file like the one below.

<?xml version="1.0" encoding="UTF-8" ?>
<hoge>
  <fuga id="1" name="tarou" age="20" gender="male">example</fuga>
</hoge>

I want to output as follows


id,1
name,tarou
age,20
gender,male

You can output with the following code

python


package example;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class example {
	public static void main(String[] args) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(new File("example.xml"));
			Element hoge = doc.getDocumentElement();
			NodeList fugaList = hoge.getChildNodes();

			for(int i=0; i<fugaList.getLength(); i++) {
				Node fuga = fugaList.item(i);
				if(fuga.getNodeType()==Node.ELEMENT_NODE) {
					//Now get the list of attributes
					NamedNodeMap nnm = fuga.getAttributes();
					for(int j=0; j<nnm.getLength(); j++) {
						Node fugaNameNode = nnm.item(j);/
                        //Output attribute and value
						System.out.println(fugaNameNode.getNodeName()+","+fugaNameNode.getNodeValue());
					}
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

result


age,20
gender,male
id,1
name,tarou

Postscript

It seems that the output order does not match. NamedNodeMap does not seem to guarantee the order

Recommended Posts

Get attributes and values from an XML file in Java
Reverse Enum constants from strings and values in Java
[Java] Program example to get the maximum and minimum values from an array
[Android development] Get an image from the server in Java and set it in ImageView! !!
Get Null-safe Map values in Java
Easily get an integer from a system property in Java
Get a non-empty collection from an Optional stream in java
Note No. 1 "Counting and displaying duplicate values in an array" [Java]
How to get the length of an audio file in java
Get history from Zabbix server in Java
[Java8] Search the directory and get the file
When calling println etc. from an external Java class file in Processing
How to get Class from Element in Java
Capture and save from selenium installation in Java
Get unixtime (seconds) from ZonedDateTime in Scala / Java
[Java] Get multiple values from one return value
[Java] Get a random value from an array
[Android] Get random keys and values from HashMap
Generate OffsetDateTime from Clock and LocalDateTime in Java
[Java] Get KFunction from Method / Constructor in Java [Kotlin]
[Java] Convert and import file values with OpenCSV
Format XML in Java
[Java] Get the file in the jar regardless of the environment
[Java] Get the file path in the folder with List
Gzip-compress byte array in Java and output to file
JSON in Java and Jackson Part 1 Return JSON from the server
Get EXIF information in Java
Get weather forecasts from Watson Weather Company Data in simple Java
Implement Java Interface in JRuby class and call it from Java
Get information in an instance and calculate numbers Standard version
What happened in "Java 8 to Java 11" and how to build an environment
Correct the character code in Java and read from the URL
Generate AWS Signature V4 in Java and request an API
Generate Stream from an array of primitive types in Java
Implement XML signature in Java
[Java] Get the dates of the past Monday and Sunday in order
[Java] Get data from DB using singleton service in Spring (Boot)
After switching between Java 8 and 11 versions, an error occurs in confirmation
Sample to read and write LibreOffice Calc fods file in Java 2021
[Java] How to convert from String to Path type and get the path
Read Java properties file in C #
Generate HashMap from XML resource file
Encoding and Decoding example in Java
Get country from IP address (Java)
Java arguments, return values and overloads
Run a batch file from Java
Unzip the zip file in Java
[Java] Declare and initialize an array
Try an If expression in Java
Log output to file in Java
StringBuffer and StringBuilder Class in Java
Write keys and values in Ruby
About go get and go install from Go1.16
Understanding equals and hashCode in Java
I made an annotation in Java.
About file copy processing in Java
Get stuck in a Java primer
Hello world in Java and Gradle
Run an external process in Java
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript
Sample code to get key JDBC type values in Java + H2 Database