java で XML をパースしてタグの属性値を取得する方法

javaでは、XMLの解析およびタグの属性値の取得にDOM(Document Object Model)を使用できます。簡単なコードの例を以下に示します。

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class XMLParser {
public static void main(String[] args) {
try {
// 创建一个DocumentBuilderFactory对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 创建一个DocumentBuilder对象
DocumentBuilder builder = factory.newDocumentBuilder();
// 使用DocumentBuilder对象的parse()方法解析XML文件,返回一个Document对象
Document document = builder.parse("example.xml");
// 获取XML文件的根元素
Element rootElement = document.getDocumentElement();
// 获取所有名为"book"的子元素
NodeList bookNodes = rootElement.getElementsByTagName("book");
// 遍历所有"book"元素
for (int i = 0; i < bookNodes.getLength(); i++) {
// 获取当前的"book"元素
Element bookElement = (Element) bookNodes.item(i);
// 获取"book"元素的属性值
String id = bookElement.getAttribute("id");
String title = bookElement.getAttribute("title");
String author = bookElement.getAttribute("author");
// 打印属性值
System.out.println("Book " + (i+1) + " - id: " + id);
System.out.println("Book " + (i+1) + " - title: " + title);
System.out.println("Book " + (i+1) + " - author: " + author);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

「example.xml」という名前のXMLファイルがあり、複数の「book」という要素があり、それぞれに「id」、「title」、「author」という属性があるとこのコードでは仮定しています。コードはDOMを使ってXMLファイルをパースし、「book」要素の各属性の値を取得します。

bannerAds