gpt4 book ai didi

java - 使用java获取XML的某些值

转载 作者:行者123 更新时间:2023-12-01 16:30:50 25 4
gpt4 key购买 nike

我的 XML 如下。如果 EServiceId 是“ESRVC2”,如何使用 Java 循环并检索标签 ClientInfo 的值?

<EServiceInfo>
<EServiceId>ESRVC1</EServiceId>
<Clients>
<ClientInfo>
<ClientEntityID>T1511111F</ClientEntityID>
<ClientEntityType>UEN</ClientEntityType>
</ClientInfo>
<ClientInfo>
<ClientEntityID>190000001W</ClientEntityID>
<ClientEntityType>UEN</ClientEntityType>
</ClientInfo>
</Clients>
</EServiceInfo>
<EServiceInfo>
<EServiceId>ESRVC2</EServiceId>
<Clients>
<ClientInfo>
<ClientEntityID>T1522222F</ClientEntityID>
<ClientEntityType>UEN</ClientEntityType>
</ClientInfo>
<ClientInfo>
<ClientEntityID>190000002W</ClientEntityID>
<ClientEntityType>UEN</ClientEntityType>
</ClientInfo>
</Clients>
</EServiceInfo>

最佳答案

这是我尝试过的答案。但看起来它会返回所有 4 个 ClientInfo。

NodeList nEserviceInfoList = doc.getElementsByTagName("EServiceInfo");
for (int i = 0; i < nEserviceInfoList.getLength(); i++) {

Node nNode = nEserviceInfoList.item(i);
System.out.println("\nCurrent Element: " + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) nNode;
Node node1 = elem.getElementsByTagName("EServiceId").item(0);
String nEServiceId = node1.getTextContent();

System.out.println("EServiceId: " + nEServiceId);

NodeList nClientList = doc.getElementsByTagName("ClientInfo");

for (int j = 0; j < nClientList.getLength(); j++) {

Node nClientNode = nClientList.item(j);

System.out.println("\nCurrent Element: " + nClientNode.getNodeName());
if (nClientNode.getNodeType() == Node.ELEMENT_NODE) {
Element elemClient = (Element) nClientNode;
Node node3 = elemClient.getElementsByTagName("ClientEntityID").item(0);
String nClientEntityID = node3.getTextContent();

Node node4 = elemClient.getElementsByTagName("ClientEntityType").item(0);
String nClientEntityType = node4.getTextContent();

System.out.println("ClientEntityID: "+ nClientEntityID);
System.out.println("ClientEntityType: "+ nClientEntityType);

}
}
}
}

关于java - 使用java获取XML的某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62046544/

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