简体   繁体   English

获取节点内节点的值

[英]Get the value of nodes inside a node

I've been trying to find a clear solution for my problem since every explanation I've found until now its confusing (for me at least).我一直在努力为我的问题找到一个明确的解决方案,因为到目前为止我发现的每一个解释都令人困惑(至少对我而言)。

I've tried DOM readers but I can't complement it with this file since its a more complex XML file.我试过 DOM 阅读器,但我不能用这个文件来补充它,因为它是一个更复杂的 XML 文件。

My XML file:我的 XML 文件:

<Order>
  <OrderID>
    <OrderConfirmationDate>
      <Date>
       <Year>2000</Year>
       <Month>10</Month>
       <Day>06</Day>
      </Date>
    </OrderConfirmationDate>
  <Adress>
    <Name>Papel do Porto</Name>
      <Address1>Rua da Alegria</Address1>
      <Address2>nº1</Address2>
      <City>Porto</City>
      <PostalCode>4000-032</PostalCode>
      <Country ISOCountryCode="PT">Portugal</Country>
    </NameAddress>

This is the code I've understood until now这是我到目前为止所理解的代码

dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();
            
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

So, I can easily get the root of document with getDocumentElement() .因此,我可以使用getDocumentElement()轻松获取文档的根目录。 And I can easily get a node of the root with getNodeName() .我可以使用getNodeName()轻松获取根节点。

But how do I get the "node.getNodeName(). (in this case I mean to get the <OrderConfirmationDate> out of <OrderID> ) Also, I've read that tags like <Year> and <Month> are Ids of the node <Date> .但是我如何获得"node.getNodeName(). (在这种情况下,我的意思是从<OrderID>中获取<OrderConfirmationDate> )另外,我读过像<Year><Month>这样的标签是节点<Date>

To select a particular node, you can use a XPath expression.要 select 特定节点,可以使用XPath表达式。

XPath xpath = XPathFactory.newDefaultInstance().newXPath();
XPathExpression expr = xpath.compile("//OrderConfirmationDate/Date");
Element orderConfirmationDateElement = (Element) expr.evaluate(doc, XPathConstants.NODE);
        

Then to go through the node's children:然后通过节点的子节点到 go:

NodeList dateChildren = orderConfirmationDateElement.getChildNodes();
for(int i = 0; i < dateChildren.getLength(); i++) {
    if (dateChildren.item(i).getNodeType() == Node.ELEMENT_NODE) {
        System.out.println(dateChildren.item(i).getNodeName() + ": " + dateChildren.item(i).getTextContent());
    }
}

Output: Output:

Year: 2000
Month: 10
Day: 06

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM