2016-03-02 106 views
0

我有一个情况在这里,我需要解析以下XML:解析有两个相同的孩子一个XML节点

<Attributes> 
    <Map> 
     <entry key="band" value="25" /> 
     <entry key="triggerSnapshots"> 
      <value> 
       <Map> 
        <entry key="AttributeChange"> 
         <value> 
          <Attributes> 
           <Map> 
            <entry key="band" value="45" /> 
           </Map> 
          </Attributes> 
         </value> 
        </entry> 
        <entry key="ManagerTransfer" value="7262079" /> 
        <entry key="needsCreateProcessing"> 
         <value> 
          <Boolean>true</Boolean> 
         </value> 
        </entry> 
       </Map> 
      </value> 
     </entry> 
    </Map> 
</Attributes> 

问题:

  1. 在上面的XML我需要皮卡输入密钥的值为band=25,而不是band=45的输入密钥。当我使用解析我的XML:

    NodeList nodes = doc.getElementsByTagName("entry");

我第一次拿到带价值25并将其存储在地图中,然后当我带值45在地图乐队值25得到由覆盖45。我只需要解析XML的方式,我得到的带值为25而不是45

+0

如果XML并不大的特定XML节点和值,那么我建议的XPath parser..in你可以把整个路径如 XPath xpath = XPathFactory.newInstance()。newXPath(); map =(String)xpath.evaluate(“/ Attributes/Map/entry/value/Map”,doc,XPathConstants.STRING); –

+0

这个嵌套是否有限制? –

回答

0

您可以简单地把doc.getElementsByTagName("entry").item(0) ,因为这将得到第一个项目是“条目”。但这不是最好的选择。

可能是最好看的XPath,并得到你想要xpath.compile("/Attributes/Map/entry")

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder; 
builder = factory.newDocumentBuilder(); 
InputSource input = new InputSource(new StringReader(xmlString)); 
org.w3c.dom.Document doc = builder.parse(input); 
XPath xpath = XPathFactory.newInstance().newXPath(); 
javax.xml.xpath.XPathExpression expr= xpath.compile("/Attributes/Map/entry[@key='band']/@value"); 
System.out.println(expr.evaluate(doc, XPathConstants.STRING)); 

More on XPath here

相关问题