Sahil
Sahil

Reputation: 1983

How to extract value from this XML in JSP

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!
            }
    %>

Upvotes: 1

Views: 7031

Answers (1)

duffy356
duffy356

Reputation: 3718

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");
    }

Upvotes: 3

Related Questions