2014-03-03 71 views
1

我知道有很多鏈接,但我找不到解決方案。根據我的搜索我想出了一些代碼:XML獲取特定屬性的節點值

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

這是我的xml文件:

<?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> 

我想「字段名稱=‘身份證’的價值「這是5386.對不起,如果我只是重新發布,但我真的無法得到答案。

回答

1

您的代碼正在獲取名稱屬性等於「Id」的Field節點。您可以更改XPath表達式,以獲取name屬性爲「Id」的元素的Value節點中的元素文本。因此,XPath表達式應該是:

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

然後在for循環更改代碼以

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

請注意,您必須使用此方法自行處理連接多個文本節點。通過使用'string(...)'函數讓XPath引擎爲你做這件事通常更簡單。 – Karsten

1

此XPath會找到正確的價值元素://Field[@Name="id"]/Value

您還可以得到的XPath通過表達式string(//Field[@Name="id"]/Value)返回元素的連接文本內容,這可能是最簡單的方法。請注意,在這種情況下,您應該直接從expr.evaluate獲取一個字符串,而不是NodeList。