[英]How to read XML file in Java without tagName
我需要在 java 中讀取文件 xml ,xmd 文檔如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<Provider>
<Invoice>256848</Invoice>
<InvoiceType>Paper</InvoiceType>
<Phone>0554334434</Phone>
<InvoiceDate>20091213</InvoiceDate>
<CustomerRequest>
<Article>
<ArticleCode>PE4</ArticleCode>
<ArticleDescription>Pen</ArticleDescription>
<DeliveryDate>20091231</DeliveryDate>
<Price>150</Price>
</Article>
</CustomerRequest>
<CustomerInfo>
<CustomerID>6901</CustomerID>
<CustomerAddress> Houghton Street</CustomerAddress>
<CustomerCity>London</CustomerCity>
</CustomerInfo>
</Provider>
問題是文檔的內容可以改變,通過包含其他標簽和許多可以具有隨機級別的嵌套標簽,有沒有辦法在不指定標簽名稱的情況下以動態方式擁有文檔的所有標簽和值? 謝謝
由於 XML 構建為樹,因此您需要使用遞歸:
假設這是您的主要課程:
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder doc = docBuilderFactory.newDocumentBuilder();
Document document = doc.parse(new File("doc.xml"));
childRecusrsion(document.getDocumentElement());
}
這是遞歸:
public static void childRecusrsion(Node node) {
// do something with the current node instead of System.out
System.out.println(node.getNodeName());
NodeList nodeList = node.getChildNodes(); //gets the child nodes that you need
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
//call the recursion
childRecusrsion(currentNode);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.