共計 1311 個字符,預計需要花費 4 分鐘才能閱讀完成。
在 Java 中,可以使用 DOM(Document Object Model)解析 XML 并獲取標簽的屬性值。以下是一個簡單的示例代碼:
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” 元素的屬性值。
丸趣 TV 網 – 提供最優質的資源集合!
正文完