我需要循环遍历父节点(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/