java - 如何在没有 tagName 的情况下用 Java 读取 XML 文件

标签 java xml nodes extract

我需要在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/

相关文章:

java - 从 url 显示图像,ImageView 不起作用,WebView 起作用

java - 后增量运算符和前增量运算符之间的性能差异?

c - 如何在链表末尾添加节点?

javascript - jQuery:正则表达式测试评论节点

c - 递归调用清除链表?

java - Java 自定义图形的最佳方法

java - Spring:我希望为 Web 应用程序创建一个 junit 测试 - 需要 WebApplicationContext

mysql - 迭代 JOIN

c# - SignedXml 的自定义命名空间问题

javascript - 我如何用 jquery 解析那个 xml 文件