我需要在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);
}
}
}
关于java - 如何在没有 tagName 的情况下用 Java 读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40260675/