[英]Retrieve multiple attributes with XPath
I have an XML file that's similar to this (each element has more attributes):我有一个与此类似的 XML 文件(每个元素都有更多属性):
<DocBuild>
<XMLDependency name="Name1" product="Product ABC" area="JKL" />
<XMLDependency name="Name2" product="Product DEF" area="MNO" />
<XMLDependency name="Name3" product="Product GHI" area="PQR" />
</DocBuild>
I want to retrieve each 'name' attribute and the 'area' for that element so I can build a list that looks like this (I've inserted a dash between 'name' and 'area' for clarity):我想检索该元素的每个“名称”属性和“区域”,以便我可以构建一个如下所示的列表(为了清楚起见,我在“名称”和“区域”之间插入了一个破折号):
Name1-JKL
Name2-MNO
Name3-PQR
public static Element getConfig(...) throws XPathExpressionException{
String path = MessageFormat.format("//DocBuild//XMLDependency[@name='Name1']//@area ")
}
Use some rules like regular expressions!使用一些规则,如正则表达式! In this case you must use "|"在这种情况下,您必须使用“|” which is used as OR clause.用作 OR 子句。
// Create XPathFactory object
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
String name = null;
try {
XPathExpression expr =
xpath.compile("/DocBuild/XMLDependency[@name='Name1']//@name|/DocBuild/XMLDependency[@name='Name1']//@area");
NodeList nl = (NodeList)expr.evaluate(doc,XPathConstants.NODESET);
String nameAttr = "";
for (int index = nl.getLength()-1; index >= 0; index--) {
Node node = nl.item(index);
nameAttr += node.getTextContent();
nameAttr += "-";
}
nameAttr = nameAttr.substring(0,nameAttr.lastIndexOf("-"));
System.out.println(nameAttr);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
See XPath Syntax请参阅XPath 语法
This XPath 2.0 expression,这个XPath 2.0表达式,
/DocBuild/XMLDependency/concat(@name,'-',@area)
evaluates directly to直接评估为
Name1-JKL
Name2-MNO
Name3-PQR
for your sample XML, as requested.根据要求为您的示例 XML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.