Как насчет чего-то вроде:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<title text=\"title1\">\n" +
" <comment id=\"comment1\">\n" +
" <data> abcd </data>\n" +
" <data> efgh </data>\n" +
" </comment>\n" +
" <comment id=\"comment2\">\n" +
" <data> ijkl </data>\n" +
" <data> mnop </data>\n" +
" <data> qrst </data>\n" +
" </comment>\n" +
"</title>\n";
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
DocumentTraversal traversal = (DocumentTraversal) doc;
NodeIterator iterator = traversal.createNodeIterator(
doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
//System.out.println("Element: " + ((Element) n).getTagName());
String tagname = ((Element) n).getTagName();
if(tagname.equals("title")) {
System.out.println("text=" + ((Element)n).getAttribute("text"));
}
else if(tagname.equals("comment")) {
System.out.println("id=" + ((Element)n).getAttribute("id"));
}
else if(tagname.equals("data")) {
System.out.println("data=" + ((Element)n).getTextContent());
}
else {
System.out.println("Unhandled element");
}
}
} catch (Exception e) {
e.printStackTrace();
}
Хорошо, так что вы не были довольны этим, как насчет этого:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<title text=\"title1\">\n" +
" <comment id=\"comment1\">\n" +
" <data> abcd </data>\n" +
" <data> efgh </data>\n" +
" </comment>\n" +
" <comment id=\"comment2\">\n" +
" <data> ijkl </data>\n" +
" <data> mnop </data>\n" +
" <data> qrst </data>\n" +
" </comment>\n" +
"</title>\n";
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
DocumentTraversal traversal = (DocumentTraversal) doc;
NodeIterator iterator = traversal.createNodeIterator(
doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
//System.out.println("Element: " + ((Element) n).getTagName());
String tagname = ((Element) n).getTagName();
NamedNodeMap map = ((Element)n).getAttributes();
if(map.getLength() > 0) {
for(int i=0; i<map.getLength(); i++) {
Node node = map.item(i);
System.out.println(node.getNodeName() + "=" + node.getNodeValue());
}
}
else {
System.out.println(tagname + "=" + ((Element)n).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}