我有以下 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()"
爪哇:
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 的新手。