Return 来自已解析 XML 文档的 NodeList 的字符串值
Return string values of NodeList from a parsed XML doc
给定 xml 片段:
<AddedExtras>
<AddedExtra Code="1234|ABCD" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="5678|EFGH" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="9111|ZXYW" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="9188|ZXYF" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="9199|ZXYG" Quantity="1" Supplier="BDA"/>
</AddedExtras>
下面的代码片段将上面的 xml 作为解析后的文档读取,并使用 xpath 表达式提取 'Code' 属性:
public String getNodeValuesFromNodeList(Document doc, String expression){
NodeList nodeList = null;
try {
nodeList = (NodeList) xpath.compile(expression).evaluate(doc, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return nodeList.toString();
}
returned 列表是一个对象 (org.apache.xml.dtm.ref.DTMNodeList@58cf8f94) 而不是字符串列表 - 我如何 return nodeList 使其 return以下是字符串列表:
Code="1234|ABCD
Code="5678|EFGH
Code="9111|ZXYW
Code="9188|ZXYF
Code="9199|ZXYG
那我怎么只return前2个(举个例子)?
如果您的 XPath 表达式选择属性,并且您想要属性的值,那么您可以使用类似于以下的循环:
List<String> codes = new ArrayList<>();
for (int i = 0; i < nodeList.getLength(); ++i) {
Attr attr = (Attr)nodeList.item(i);
codes.add(attr.getValue());
}
给定 xml 片段:
<AddedExtras>
<AddedExtra Code="1234|ABCD" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="5678|EFGH" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="9111|ZXYW" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="9188|ZXYF" Quantity="1" Supplier="BDA"/>
<AddedExtra Code="9199|ZXYG" Quantity="1" Supplier="BDA"/>
</AddedExtras>
下面的代码片段将上面的 xml 作为解析后的文档读取,并使用 xpath 表达式提取 'Code' 属性:
public String getNodeValuesFromNodeList(Document doc, String expression){
NodeList nodeList = null;
try {
nodeList = (NodeList) xpath.compile(expression).evaluate(doc, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return nodeList.toString();
}
returned 列表是一个对象 (org.apache.xml.dtm.ref.DTMNodeList@58cf8f94) 而不是字符串列表 - 我如何 return nodeList 使其 return以下是字符串列表:
Code="1234|ABCD
Code="5678|EFGH
Code="9111|ZXYW
Code="9188|ZXYF
Code="9199|ZXYG
那我怎么只return前2个(举个例子)?
如果您的 XPath 表达式选择属性,并且您想要属性的值,那么您可以使用类似于以下的循环:
List<String> codes = new ArrayList<>();
for (int i = 0; i < nodeList.getLength(); ++i) {
Attr attr = (Attr)nodeList.item(i);
codes.add(attr.getValue());
}