我有如下的XML。如果EServiceId是使用Java的“ ESRVC2”,如何循环和获取Tag 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);
}
}
}
}