XML : Iterating only one xml tag using Java

I'm iterating an XML object, but its fetching only one XML tag value. Please check the code. It is printing only the first tag value "abd5fd81-2bd6-4479-9d60-61fe533a13b7".

  public class sample {    /**   * @param args   */  private final static String XML_DATA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +          "<list>" +          "<string>abd5fd81-2bd6-4479-9d60-61fe533a13b7</string>" +          "<string>e127393b-343b-433c-87fc-27289758cca8</string>" +          "<string>753f79fe-a1d2-4383-b5c9-3ec8aa6b7e65</string>" +          "<string>2c71f819-65a6-4b08-8870-e71b1c770992</string>" +          "<string>ad22d8c0-8187-4243-8189-92e94c969208</string>" +          "<string>e6e70ab9-6149-4dfd-9d88-e27ec419847e</string>" +          "<string>87d8566b-4c8a-4ef0-9fa9-c7b8805e5631</string>" +          "<string>1309a729-20b4-40bb-96c8-46c96f205e60</string>" +          "<string>5e78b822-d472-4f02-859d-de36183c5d01</string>" +          "<string>410c70fb-8b05-47ef-bfbf-29284e45c8d3</string>" +          "</list>";    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {      // TODO Auto-generated method stub      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();      DocumentBuilder builder;      builder = factory.newDocumentBuilder();      InputSource is = new InputSource();      is.setCharacterStream(new StringReader(XML_DATA));        Document doc = builder.parse(is);      NodeList nodes = doc.getElementsByTagName("list");      for (int i = 0; i < nodes.getLength(); i++) {          Element element = (Element) nodes.item(i);          NodeList name = element.getElementsByTagName("string");          Element line = (Element) name.item(0);          System.out.println("String: " + getCharacterDataFromElement(line));              }             }    private static String getCharacterDataFromElement(Element e) {      // TODO Auto-generated method stub      Node child = e.getFirstChild();      if (child instanceof org.w3c.dom.CharacterData) {         org.w3c.dom.CharacterData cd = (org.w3c.dom.CharacterData) child;         return cd.getData();      }      return "?";  }    }    

Is there anything missing in the code?

No comments:

Post a Comment