0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaでXMLファイルから属性と値を取得する

Last updated at Posted at 2020-08-26

####以下のようなxmlファイルから、fugaタグの属性と値を取得したいとします。

<?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

####以下のコードによって出力することが出来ます

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) {
					// ここで、attributeの一覧を取得します
					NamedNodeMap nnm = fuga.getAttributes();
					for(int j=0; j<nnm.getLength(); j++) {
						Node fugaNameNode = nnm.item(j);/
                        // attributeとvalueを出力します
						System.out.println(fugaNameNode.getNodeName()+","+fugaNameNode.getNodeValue());
					}
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

####結果


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

####追記

出力順序が一致していないっぽいです。
NamedNodeMapは順序を担保していない様子

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?