java - 通过 XPath 表达式提取多个属性节点值的值
问题描述
如何通过 XPath 表达式提取多个属性节点的值?
一个示例 XML 文件是:
<tag1>
<tag2>
<tag3 id="1">
<tage4>
<tage4code code="1">
<tag5>
<tage4Value Day="14" Month="Oct" Year="2000" />
</tag5>
<tag5>
<tage4Value Month="Oct" Year="2001" />
</tag5>
<tag5>
<tage4Value Year="2002" />
</tag5>
<tag5>
<tage4Value Day="1" Month="Jan" Year="1999" />
</tag5>
<tag5>
<tage4Value Year="1940" />
</tag5>
</tage4code>
</tage4>
</tag3>
</tag2>
</tag1>
到目前为止,我有这个 XPath 字符串:
XPathExpression expr = xpath.compile("concat((/tag1/tag2/tag3[@id=1]/tage4/tage4code[@code=1]/tag5/tage4Value/@Day, '/' , /tag1/tag2/tag3[@id=1]/tage4/tage4code[@code=1]/tag5/tage4Value/@Month, '/', /tag1/tag2/tag3[@id=1]/tage4/tage4code[@code=1]/tag5/tage4Value/@Year)");
NodeList combination1 = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int a = 0; a <= combination1.getLength(); a++) {
System.out.println("date : " + combination.item(a).getNodeValue());
}
我的预期结果
2000 年 10 月 14 日 2001 年 10 月 2002 年 1999 年 1 月 1940 年
有人可以帮助纠正我的 XPathExpression
解决方案
XPath 2.0 解决方案:
tokenize(replace(replace(replace(substring-after(string-join(//tag5/*|//tag5//@*,","),","),",,","%"),","," ")," ","/"),"%")
输出 :
String='14/Oct/2000'
String='Oct/2001'
String='2002'
String='1/Jan/1999'
String='1940'
XPath 1.0 解决方案:
concat(translate(normalize-space(concat((//tage4Value)[1]/@Day," ",(//tage4Value)[1]/@Month," ",(//tage4Value)[1]/@Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[2]/@Day," ",(//tage4Value)[2]/@Month," ",(//tage4Value)[2]/@Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[3]/@Day," ",(//tage4Value)[3]/@Month," ",(//tage4Value)[3]/@Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[4]/@Day," ",(//tage4Value)[4]/@Month," ",(//tage4Value)[4]/@Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[5]/@Day," ",(//tage4Value)[5]/@Month," ",(//tage4Value)[5]/@Year))," ","/"))
输出 :
String='14/Oct/2000|Oct/2001|2002|1/Jan/1999|1940'
或使用新行分隔符:
concat(translate(normalize-space(concat((//tage4Value)[1]/@Day," ",(//tage4Value)[1]/@Month," ",(//tage4Value)[1]/@Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[2]/@Day," ",(//tage4Value)[2]/@Month," ",(//tage4Value)[2]/@Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[3]/@Day," ",(//tage4Value)[3]/@Month," ",(//tage4Value)[3]/@Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[4]/@Day," ",(//tage4Value)[4]/@Month," ",(//tage4Value)[4]/@Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[5]/@Day," ",(//tage4Value)[5]/@Month," ",(//tage4Value)[5]/@Year))," ","/"))
输出 :
String='14/Oct/2000
Oct/2001
2002
1/Jan/1999
1940'