0
0

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 1 year has passed since last update.

DOMを利用してXMLを読み込むサンプル

Posted at

JavaにはXMLを扱うライブラリがいくつか用意されています。そのうちDOMと呼ばれるライブラリを使ってXMLを読みこむサンプルをここでは紹介します。

自分用のメモの側面があります。XMLを読み込むスクリプトを書くことがたまにあり、そのたびにググらないようにするための記事です。

ECサイトの注文情報を記載したorder.xmlがあるとします。

order.xml
<?xml version="1.0"?>
<Orders>
	<Order Customer="高津一郎" Address="神奈川県川崎市高津区" Phone="0000-1111-2222">
		<Product>ボールペン</Product>
		<Price>100</Price>
		<Quantity>1</Quantity>
	</Order>
	<Order Customer="中原二郎" Address="神奈川県中原市中原区" Phone="1111-2222-3333">
		<Product>消しゴム</Product>
		<Price>150</Price>
		<Quantity>2</Quantity>
	</Order>
	<Order Customer="多摩三郎" Address="神奈川県川崎市多摩区" Phone="2222-3333-4444">
		<Product>はさみ</Product>
		<Price>200</Price>
		<Quantity>4</Quantity>
	</Order>
</Orders>

このorder.xmlに対して、以下の要件があるとします。

  1. Order要素の属性すべてをPretty Printする
  2. Order要素の子要素すべてをPretty Printする

これを実現するコードは以下の通りです。

Path xmlPath = Paths.get("order.xml");
try (InputStream inputStream = Files.newInputStream(xmlPath)) {
	Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);

	// ルート要素を取得する。
	Element orders = document.getDocumentElement();

	// ルート要素の直下にあるノードの一覧を取得する。
	NodeList orderList = orders.getChildNodes();
	for (int i = 0; i < orderList.getLength(); i++) {
		// Order要素を取得する。NodeListには要素以外も格納されているので、要素だけを取得するようにする。
		if (orderList.item(i).getNodeType() != Node.ELEMENT_NODE) {
			continue;
		}
		Element order = (Element) orderList.item(i);

		// Order要素の属性をすべて取得し、Pretty Printする
		NamedNodeMap attributes = order.getAttributes();
		for (int j = 0; j < attributes.getLength(); j++) {
			Attr attribute = (Attr) attributes.item(j);
			String name = attribute.getName();
			String value = attribute.getValue();
			System.out.printf("%s=%s%n", name, value);
		}

		// Order要素の直下にあるノードの一覧を取得する。
		NodeList orderDetailList = order.getChildNodes();
		for (int j = 0; j < orderDetailList.getLength(); j++) {
			// Order要素の直下にある要素を取得する。NodeListには要素以外も格納されているので、要素だけを取得するようにする。
			if (orderDetailList.item(j).getNodeType() != Node.ELEMENT_NODE) {
				continue;
			}
			Element orderDetail = (Element) orderDetailList.item(j);

			// Order要素の直下にある要素をPretty Printする。
			String tagName = orderDetail.getTagName();
			String textContent = orderDetail.getTextContent();
			System.out.printf("%s=%s%n", tagName, textContent);
		}

		System.out.println("------------------------------");
	}
} catch (IOException | SAXException | ParserConfigurationException e) {
	e.printStackTrace();
}

このプログラムを実行すると、以下のような結果が得られるはずです。

Address=神奈川県川崎市高津区
Customer=高津一郎
Phone=0000-1111-2222
Product=ボールペン
Price=100
Quantity=1
------------------------------
Address=神奈川県中原市中原区
Customer=中原二郎
Phone=1111-2222-3333
Product=消しゴム
Price=150
Quantity=2
------------------------------
Address=神奈川県川崎市多摩区
Customer=多摩三郎
Phone=2222-3333-4444
Product=はさみ
Price=200
Quantity=4
------------------------------

環境情報

D:\>javac -version
javac 17.0.3

D:\>java -version
openjdk version "17.0.3" 2022-04-19
OpenJDK Runtime Environment Temurin-17.0.3+7 (build 17.0.3+7)
OpenJDK 64-Bit Server VM Temurin-17.0.3+7 (build 17.0.3+7, mixed mode, sharing)
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?