gpt4 book ai didi

java - 在 XPath 表达式中使用整数变量 Java 从具有 namespace 的重复节点中提取信息

转载 作者:行者123 更新时间:2023-11-30 04:58:05 24 4
gpt4 key购买 nike

解决了!谢谢大家!

您的建议让我找到了答案。所以你们所有人的建议都值得感谢。

放置 int 变量的解决方案如下:

//Put my xpath into a string variable where it can evaluate my integer "counter"

String myString = "/*[local-name()='root' and namespace-uri()='DK']/*[local-name()='book' and namespace-uri()='DK']" + counter + "]/*[local-name()='item1' and namespace-uri()='DK']/*[local-name()='item2' and namespace-uri()='DK']/*[local-name()='date' and namespace-uri()='DK'][" + counter + "]"


//Then simply put that string variable into the xpath expression.
System.out.print(myString);

原始问题如下:

首先,我感谢任何帮助。预先感谢您的帮助。

我有一个需要解析的 XML 文件。

举个例子......

<root xmlns="DK">
<book>
<item1>
<item2>
<date>xxx
</date>
<date>x1x1x1
</date>
</item2>
</item1>
</book>
<book>
<item1>
<item2>
<date>yyy
</date>
<date>y1y1y1
</date>
</item2>
</item1>
</book>
</root>

所以基本上,我正在寻找带有 xxx 的节点 ,然后转到下一本书中包含 yyy 的相同节点

输入 xml 文件将包含未知数量的重复书籍,每本书的信息不同。

我选择尝试这样的事情。

// I've imported from dom4j SAXreader. I probably could use something different.
import org.dom4j.io.SAXReader;



// Variables
Document document = null;

// Take input from file
SAXReader reader = new SAXReader();
document = reader.read("E:/templates/test.xml");

int counter = 0;
int numofbooks = 0;

Element root = document.getRootElement();

for ( Iterator i = root.elementIterator("book"); i.hasNext();) {
Element element = (Element) i.next();

counter = counter + 1;
numofbooks = counter;
}

System.out.println("There are " + numofbooks + " books required for processing");
while(counter != numofbooks); {
counter = counter + 1;

System.out.print("The values are: ");

// ----- This here is my problem code ----- //
System.out.print(/*[local-name()='root' and namespace-uri()='DK']/*[local-name()='book' and namespace-uri()='DK'][counter]/*[local-name()='item1' and namespace-uri()='DK']/*[local-name()='item2' and namespace-uri()='DK']/*[local-name()='date' and namespace-uri()='DK'][counter]).getStringValue());


System.out.print(" respectively");
}

我的问题就出在这里。因为嵌套了一些具有完全相同名称的重复节点,所以我使用整数计数器变量按数字抓取它们。

我的 XPath 表达式无法理解我放入的变量“计数器”是一个整数。

我可以使用任何语法来完成这项工作吗?还是根本不可能?

提前致谢。

DK

最佳答案

您可以在 XPath 表达式中引用变量 $counter,并且可以通过定义 XPathVariableResolver 并将其与 XPathFactory 关联来从 Java API 设置该变量的值。

关于java - 在 XPath 表达式中使用整数变量 Java 从具有 namespace 的重复节点中提取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7871229/

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