【问题标题】:How to read XML file in Java without tagName如何在没有 tagName 的情况下用 Java 读取 XML 文件
【发布时间】:2016-10-26 11:06:29
【问题描述】:

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

问题是文档的内容可以改变,通过包含其他标签和许多可以具有随机级别的嵌套标签,有没有办法拥有文档的所有标签和值 在不指定标签名称的情况下以动态方式? 谢谢

【问题讨论】:

  • 是的,将其作为 DOM 文档阅读,您就拥有了所有的标签和值。
  • 事实上,几乎所有用于读取此类文档的技术(SAX、DOM、其他树模型,如 JDOM2 和 XOM、XPath、XQuery、XSLT)都可以在没有词汇知识的情况下工作。唯一真正的例外是 JAXB。
  • 你应该去DocumentBuilderFactory 。更多详情请参考here的解决方案2

标签: java xml nodes extract


【解决方案1】:

由于 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);
            }
        }
    }

【讨论】:

  • 谢谢你,正是我需要的!
猜你喜欢
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 2012-09-02
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 2017-10-24
相关资源
最近更新 更多