共計 1511 個字符,預計需要花費 4 分鐘才能閱讀完成。
要獲取 XML 節點的屬性,可以使用 Java 的 DOM 解析器來解析 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 文件的路徑。
丸趣 TV 網 – 提供最優質的資源集合!
正文完