<?xml version="1.0" encoding="UTF-8" ?>
<hoge>
  <fuga id="1" name="tarou" age="20" gender="male">example</fuga>
</hoge>
id,1
name,tarou
age,20
gender,male
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();
		}
	}
}
age,20
gender,male
id,1
name,tarou
It seems that the output order does not match. NamedNodeMap does not seem to guarantee the order
Recommended Posts