gpt4 book ai didi

java - XPath 编译行为

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:20 25 4
gpt4 key购买 nike

我正在测试我的应用程序,并意识到编译时的行为有所不同。

例如,如果我要编译的表达式是:

XPathExpression expr = xPath.compile("/DocDetails/TransactionSignature");

还有:

XPathExpression expr2 = xPath.compile("/DocDetails/" + x); 

x 被声明为字符串数据类型。

假设 expr2 中的 x 是“abc”,XPathExpression 编译时没有任何问题。

但是如果 expr2 中的 x 是“123abc”或“123”,XPathExpression 会抛出:

javax.xml.transform.TransformerException: A location step was expected following the '/' or '//' token.

只是对这种行为感到好奇..

以下是完整代码供引用:

        String document = "C:/Users/Eunice/Documents/MITS/doc.xml";
String document2 = "C:/Users/Eunice/Documents/MITS/doc2.xml";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(document);

Document doc2 = builder.parse(document2);

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression expr = xPath.compile("/DocDetails/TransactionSignature");
Node node = (Node)expr.evaluate(doc, XPathConstants.NODE);

String x = node.getTextContent();

System.out.println(x);

XPathExpression expr2 = xPath.compile("/DocDetails/" + x);
Node node2 = (Node)expr2.evaluate(doc2, XPathConstants.NODE);

if (node2 == null)
System.out.println("null");
else
System.out.println("not null " + node2.getTextContent());

这是 XML 文件:

<DocDetails>
<TransactionSignature>abc123</TransactionSignature>
</DocDetails>

最佳答案

But if x in expr2 is "123abc" OR "123", XPathExpression throws a

XML 元素名称不能以数字开头。因此你的例子相当于

XPathExpression expr2 = xPath.compile("/DocDetails/123abc");

我猜 XPath 解析器并不期望它。

您还应该提供完整的 XML。我相信它肯定不包含类似 <DocDetails><TransactionSignature>abc123</TransactionSignature><123abc>something</123abc></DocDetails> 的内容。这只是无效的 XML。

关于java - XPath 编译行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55137103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com