I want to read a multi level tags from xml(DOM) using java and the sample xml is :
test1
address1test2
address2test3
address3How to read test2 and
address2 from the above xml?I have given a sample code .. but i need to find the values dynamically.
when i am iterating bu using subclass tag, it's giving all the data. just i want to know how to get the specific data like test2 and
address2 .Below is my java code which is reading the above xml:
NodeList fList = firstWordElement
.getElementsByTagName("root");
for (int i = 0; i < fList.getLength(); i++) {
Node firstFLNode = fList.item(i);
if (firstFLNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstWdElement = (Element) firstFLNode;
NodeList firstWdList = firstWdElement.getElementsByTagName("innerclass");
for (int j = 0; j < firstWdList.getLength(); j++) {
Element firstWd1Element = (Element) firstWdList.item(j);
if (firstWd1Element.getNodeType() == Node.ELEMENT_NODE) {
String InnerName = ParseUtil.getTagValue("name", firstWd1Element);
String InnerFormat = ParseUtil.getTagValue("format", firstWd1Element);
String InnerDescription = ParseUtil.getTagValue("description", firstWd1Element);
NodeList innerClassList = firstWd1Element.getElementsByTagName("subclass");
for (int k = 0; k < innerClassList.getLength(); k++) {
Element subClassElement = (Element) innerClassList
.item(k);
if (subClassElement.getNodeType() == Node.ELEMENT_NODE) {
String InnerSubName = ParseUtil.getTagValue("name", subClassElement);
System.out.println("Innername==="+ InnerSubName);
String InnerSubFormat = ParseUtil.getTagValue("format", subClassElement);
System.out.println("Innerformat==="+ InnerSubFormat);
String InnerSubDescription = ParseUtil.getTagValue("description", subClassElement);
System.out.println("Innerdescription==="+ InnerSubDescription);
}
}
}
}
}
}
解决方案
Use XPATH APIs
You create an XPathFactory:
XPathFactory factory = XPathFactory.newInstance();
You then use this factory to create an XPath object:
XPath xpath = factory.newXPath();
The XPath object compiles the XPath expression:
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/title/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
You can then cast the result to a DOM NodeList and iterate through that to find all the titles:
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}