我知道有很多鏈接,但我找不到解決方案。根據我的搜索我想出了一些代碼: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.對不起,如果我只是重新發布,但我真的無法得到答案。
請注意,您必須使用此方法自行處理連接多個文本節點。通過使用'string(...)'函數讓XPath引擎爲你做這件事通常更簡單。 – Karsten