简体   繁体   中英

XML get value of node on a specific attribute

I know there are many links for this but I couldn't find a solution. Based on my searches I have come up with some code:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));

Document doc = builder.parse(is);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();

XPathExpression expr = xpath.compile("//Field[@Name=\"id\"]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println(nl.getLength());
for(int i=0;i<nl.getLength();i++){
    Node currentItem = nl.item(i);
    String key = currentItem.getAttributes().getNamedItem("Name").getNodeValue();
    System.out.println(key);
}

This is my xml file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Entity Type="test-folder">
<Fields>
<Field Name="item-version"/>
<Field Name="id">
    <Value>5386</Value>
</Field>
<Field Name="ver-stamp">
    <Value>2</Value>
</Field>
<Field Name="parent-id">
    <Value>5310</Value>
</Field>
<Field Name="system">
    <Value>A</Value>
</Field>
<Field Name="last-modified">
    <Value>2014-03-03 16:35:24</Value>
</Field>
<Field Name="description">
    <Value/>
</Field>
<Field Name="hierarchical-path">
    <Value>AAAAAPAADAACADC</Value>
</Field>
<Field Name="view-order">
    <Value>0</Value>
</Field>
<Field Name="name">
    <Value>TC77</Value>
</Field>
<Field Name="attachment">
    <Value/>
</Field>
</Fields>

I want to get the value of "Field Name='id'" which is 5386. Sorry if I am just re-posting this but I really couldn't get an answer.

Your code is getting the Field node with the name attribute equal to "Id". You can change the XPath expression to get the element text within the Value node of the element where the name attribute is "Id". So the XPath expression should be:

//Field[@Name=\"id\"]/Value/text()

Then change the code in the for-loop to

        Node currentItem = nl.item(i);
        System.out.println(currentItem.getNodeValue());

This XPath will find the correct Value element: //Field[@Name="id"]/Value

You can also get XPath to return the concatenated text content of the element via the expression string(//Field[@Name="id"]/Value) , this is probably the simplest approach. Note that you should directly get back a string from expr.evaluate in this case, not a NodeList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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