javaでXMLノードのプロパティを取得する方法

DOMパーサを使用してXMLドキュメントを解析することで、XMLノードのプロパティを取得できます。DOMパーサはXMLドキュメントを処理する便利な方法を提供し、ノードのプロパティを簡単に取得できます。

以下に、JavaのDOMパーサを使用してXMLノードの属性を取得する方法を示す簡単な例を示します。

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class XMLParser {
    public static void main(String[] args) {
        try {
            // 创建一个DocumentBuilderFactory对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            
            // 创建一个DocumentBuilder对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            
            // 使用DocumentBuilder对象解析XML文件,得到一个Document对象
            Document document = builder.parse("example.xml");
            
            // 获取XML文档的根元素
            Element root = document.getDocumentElement();
            
            // 获取所有名为"book"的节点
            NodeList bookList = root.getElementsByTagName("book");
            
            // 遍历所有的"book"节点
            for (int i = 0; i < bookList.getLength(); i++) {
                Element book = (Element) bookList.item(i);
                
                // 获取book节点的属性值
                String id = book.getAttribute("id");
                String title = book.getAttribute("title");
                String author = book.getAttribute("author");
                String price = book.getAttribute("price");
                
                // 打印属性值
                System.out.println("Book ID: " + id);
                System.out.println("Title: " + title);
                System.out.println("Author: " + author);
                System.out.println("Price: " + price);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上の例では、最初に DocumentBuilderFactory オブジェクトを作成し、それを使用して DocumentBuilder オブジェクトを作成します。次に、DocumentBuilder オブジェクトを使用して「example.xml」という名前の XML ファイルを解析し、Document オブジェクトを取得します。次に、getDocumentElement() メソッドを呼び出し、XML ドキュメントのルート要素を取得します。次に、getElementsByTagName() メソッドを使用して、名前が「book」のすべてのノードを取得し、それらのノードを反復処理します。反復処理中に、getAttribute() メソッドを呼び出して各 book ノードの属性値を取得します。

「example.xml」をコード内の実際のXMLファイルへのパスに置き換えてください。

bannerAds