1

I have an XML as below (has 100s of line):

    <root>

      <data v="1.0">

        <cellimage counter="0" cash_filename="C:\Temp\_TempFolder\39d437f08cc302876a70a0f91b137991_h.jpg" width="94" height="141" />

        <cellimage counter="1" cash_filename="C:\Temp\_TempFolder\39d437f08cc302876a70a0f91b137991_h.jpg" width="94" height="141" />

      </data>

    </root>

Can anyone please tell me how I can loop through it and extract attributes like 'counter' and 'cash_filename' from the above XML file in JSP.

So far I have following code:

    <%
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("http://localhost:8080/data.xml");

        NodeList nl = doc.getElementsByTagName("cellimage");
            for (int i = 0; i < nl.getLength(); i++) {
                //Not sure what to do here!
            }
    %>
Sahil
  • 1,959
  • 6
  • 24
  • 44
  • What you have tried? any basic tutorial on DOM with Java should guide you. – sudmong Apr 16 '13 at 10:26
  • I tried a tutorial from http://www.easywayserver.com/blog/java-read-xml-file/ But because that tutorial is working with child elements where I need to work with attributes the code in the tutorial does not work for me and throws error because of null pointer. – Sahil Apr 16 '13 at 10:29

1 Answers1

3

you can get your items quite simple:

NodeList nl = doc.getElementsByTagName("cellimage");
    Element el;
    Integer counter;
    String fName;

    for (int i = 0; i < nl.getLength(); i++) {
        //Not sure what to do here!
        el = (org.w3c.dom.Element) nl.item(i);
        counter = Integer.valueOf(el.getAttribute("counter"));
        fName = el.getAttribute("cash_filename");
    }
duffy356
  • 3,678
  • 3
  • 32
  • 47