gpt4 book ai didi

java - xpath 获取子节点相对于 XML 中父节点的位置

转载 作者:行者123 更新时间:2023-12-01 17:24:07 25 4
gpt4 key购买 nike

我需要循环遍历父节点(callEvents)中的所有子节点,并每次保存子节点的位置。(第一次调用事件,第二次调用事件...)。我正在堆栈如何获取父节点java/xpath中每个子节点的位置?

假设我有以下 xml:

<callEvents>
<gprsCall>...</gprsCall>
<gprsCall>...</gprsCall>
<mobileOrigintaedCall>...</mobileOrigintaedCall>
<gprsCall>...</gprsCall>
<gprsCall>...</gprsCall>
</callEvents>

所以代码应该返回:

  • 我的第一个 gprsCall 位置 = 1
  • 我的第二个 gprsCall 位置 = 2
  • 我的第一个 mobileOriginatedCall 位置 = 3
  • 我的第三个 gprsCall 位置 = 4
  • 我的第四个 gprsCall 位置 = 5

最佳答案

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathConstants;
import java.io.StringReader;
import org.xml.sax.InputSource;

class myxml {
static final String xml = "<callEvents>\n"
+ "<gprsCall>...</gprsCall>\n"
+ "<gprsCall>...</gprsCall>\n"
+ "<mobileOrigintaedCall>...</mobileOrigintaedCall>\n"
+ "<gprsCall>...</gprsCall>\n"
+ "<gprsCall>...</gprsCall>\n"
+ "</callEvents>";

public static void main (String... args) throws Throwable {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));

XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("/callEvents/*");
NodeList nodelist = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodelist.getLength(); i++) {
System.out.println("Position: " + (i + 1)
+ ", name: " + nodelist.item(i).getNodeName());
}
} catch (Throwable e) {
throw e;
}
}
}

关于java - xpath 获取子节点相对于 XML 中父节点的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61236066/

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