我有以下XML:
<thoughts>
<thought>
<id>1</id>
<category>Leadership</category>
<what>sometext</what>
<who>sometext</who>
</thought>
<thought>
<id>2</id>
<category>Leadership</category>
<what>sometext</what>
<who>sometext</who>
</thought>
... 100s of category Leadership
<thought>
<id>1</id>
<category>Love</category>
<what>sometext</what>
<who>sometext</who>
</thought>
<thought>
<id>2</id>
<category>Love</category>
<what>sometext</what>
<who>sometext</who>
</thought>
... 100s of category Love
... and so on up to about ten categories
</thoughts>
我想为给定的ID和类别选择思想(什么)。我在Java中这样做。我尝试了以下方法:
"/thought[id='1']/thought[category='Love']/what/text()"
Java:
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
XPathExpression expr1 = xPath.compile("/thought[id='1']/thought[category='Love']/what/text()");
Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
NodeList nodes1 = (NodeList) result1;
我也尝试过XPathExpressions:
/thoughts/thought[id='1']/thought[category=`Love`]/what/text()
我是XML和XPath的新手。
答案 0 :(得分:1)
使用强>:
/*/thought[id = '1' and category = 'Love']/what
这会选择what
个元素的thought
元素,该元素具有id
子元素,其字符串值为"1"
且具有category
字符串值为"Love"
的子元素,并且thought
元素)是XML文档顶部元素的子元素。
如果您需要上面选择的元素的文本节点子节点,请使用:
/*/thought[id = '1' and category = 'Love']/what/text()
如果您只需要上述文本节点(第一个)的字符串值,请使用:
string(/*/thought[id = '1' and category = 'Love']/what)
基于XSLT的验证:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select="/*/thought[id = '1' and category = 'Love']/what"/>
============
<xsl:copy-of select="/*/thought[id = '1' and category = 'Love']/what/text()"/>
============
<xsl:copy-of select="string(/*/thought[id = '1' and category = 'Love']/what)"/>
</xsl:template>
</xsl:stylesheet>
将此转换应用于以下XML文档(提供的文档具有所需节点的不同值):
<thoughts>
<thought>
<id>1</id>
<category>Leadership</category>
<what>sometext</what>
<who>sometext</who>
</thought>
<thought>
<id>2</id>
<category>Leadership</category>
<what>sometext</what>
<who>sometext</who>
</thought>
... 100's of with category Leadership
<thought>
<id>1</id>
<category>Love</category>
<what>some Love text 1</what>
<who>sometext</who>
</thought>
<thought>
<id>2</id>
<category>Love</category>
<what>sometext</what>
<who>sometext</who>
</thought>
... 100's of with category Love
... and so on up to about ten categories
</thoughts>
评估三个XPath表达式,并将这些评估的结果复制到输出,由一个方便的分隔符直观地分开:
<what>some Love text 1</what>
============
some Love text 1
============
some Love text 1
<强>更新强>:
在评论中,OP已添加了一项要求,即不仅应选择what
,还应选择who
。
以下是此案例的相应新XPath表达式:
/*/thought[id = '1' and category = 'Love']/*[self::what or self::who]
/*/thought[id = '1' and category = 'Love']/*[self::what or self::who]/text()
答案 1 :(得分:0)