我正在尝试使用 Xpath 来解析 xml 字符串,但我不知道如何使用表达式来检索我想要的内容。
我有以下 xml 内容:
<root1>
<root2>
<A>something</A>
<B>something</B>
<C>
<D>
<E>DataE</E>
<F>DataF</F>
<G>something</G>
<H>something</H>
<I>
<J>
<K>DataK</K>
<L>DataL</L>
</J>
</I>
</D>
<D>
<E>DataE_ERROR</E>
<F>DataF</F>
<G>something</G>
<H>something</H>
<I>
<J>
<K>DataK</K>
<L>DataL</L>
</J>
</I>
</D>
</C>
</root2>
</root1>
例如,当 E 的值为 DataE 时,我想获取 F、K、L 的值。
我正在使用这个 Xpath,但找不到合适的表达式!
这是我的java代码:
public void getit()
{
String xml = "The xml above";
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document d = b.parse(new InputSource(new StringReader(xml)));
d.getDocumentElement().normalize();
// No idea ! how can i make it work by testing the value of E
String expression = "//E/text()|//F/text()|//K/text()|//L/text()";
XPath xPath = XPathFactory.newInstance().newXPath();
Object result = xPath.compile(expression).evaluate(d, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
最佳答案
为了确保查询正常工作,我修改了示例 XML 如下...
<root1>
<root2>
<A>something</A>
<B>something</B>
<C>
<D>
<E>DataE</E>
<F>DataF 1</F>
<G>something</G>
<H>something</H>
<I>
<J>
<K>DataK 1</K>
<L>DataL 1</L>
</J>
</I>
</D>
<D>
<E>DataE_ERROR</E>
<F>DataF 2</F>
<G>something</G>
<H>something</H>
<I>
<J>
<K>DataK 2</K>
<L>DataL 2</L>
</J>
</I>
</D>
</C>
</root2>
</root1>
魔法就在这里......
String expression = "//F[ancestor::D/E[text()='DataE']]|//K[ancestor::D/E[text()='DataE']]|//L[ancestor::D/E[tex
基本上,这就是……
找到任何 F
节点,其祖先包含 D
,E
的子节点的文本等于 DataE
或 ...
现在,这很重要,您可以使用 ../
来查找父节点,但是 K
和 L
被埋在子节点中节点,我不确定它们是更深还是更浅,所以我选择了这种方法。
您可能需要对其进行一些改进,但我认为 D/E
的关系很重要。
有了这个(以及下面的示例),我能够生成以下输出...
Found DataF 1
Found DataK 1
Found DataL 1
可运行示例:
public class TestXPath {
public static void main(String[] args) {
String xml = "The xml above";
try {
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document d = b.parse(new File("Values.xml"));
d.getDocumentElement().normalize();
String expression = "//F[ancestor::D/E[text()='DataE']]|//K[ancestor::D/E[text()='DataE']]|//L[ancestor::D/E[text()='DataE']]";
XPath xPath = XPathFactory.newInstance().newXPath();
Object result = xPath.compile(expression).evaluate(d, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
System.out.println("Found " + node.getTextContent());
}
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | DOMException exp) {
exp.printStackTrace();
}
}
}
关于java - Xpath Java 通过测试值获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22493545/