I have an issue of iterating xml in java .I have a root node as element,inside element tag two sub nodes are there, but i am getting node length as 1. can any one guide me how to rectify it. I have mentioned my code below.
import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.CharacterData; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class Test { public static void main(String arg[]) throws Exception{ String xmlRecords = "<data><employee><name>A</name><title>Manager</title><name>B</name><title>Manager</title></employee></data>"; DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlRecords)); Document doc = db.parse(is); NodeList nodes = doc.getElementsByTagName("employee"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList name = element.getElementsByTagName("name"); Element line = (Element) name.item(i); System.out.println("Name: " + getCharacterDataFromElement(line)); NodeList title = element.getElementsByTagName("title"); line = (Element) title.item(i); System.out.println("Title: " + getCharacterDataFromElement(line)); } } public static String getCharacterDataFromElement(Element e) { Node child = e.getFirstChild(); if (child instanceof CharacterData) { CharacterData cd = (CharacterData) child; return cd.getData(); } return ""; } }
Result:
Name: A Title: Manager
Expected Output:
Name: A Title: Manager Name: B Title: Manager
No comments:
Post a Comment