Ignox
Ignox

Reputation: 147

How can I read Xml attributes using Java?

Given an xml document that looks like the following:

 <?xml version="1.0"?>
     <xml_api_reply version="1">
      <weather section="0" row="0" mobile_zipped="1" mobile_row="0"     tab_id="0" module_id="0">
        <forecast_information>
            <city data="Cordova, Andalusia"/>
            <postal_code data="cordoba"/>
            <latitude_e6 data=""/>
            <longitude_e6 data=""/>
            <forecast_date data="2012-07-18"/>
            <current_date_time data="1970-01-01 00:00:00 +0000"/>
            <unit_system data="SI"/>
         </forecast_information>

I want to show city data, postal_code and date attributes with help of System.out.println().

Any idea?

Upvotes: 2

Views: 35596

Answers (6)

Rondo
Rondo

Reputation: 3721

Just a little cleaned up with type declarations, basic null checks:

Start with any node in the value of 'dom'

NodeList l = dom.getElementsByTagName("tagname");

for (int j=0; j<l.getLength(); ++j) {
    Node prop = l.item(j);
    NamedNodeMap attr = prop.getAttributes();
    if (null != attr) {
        Node p = attr.getNamedItem("data");
        log.debug(p.getNodeValue());
    }
}

Upvotes: 3

Ignox
Ignox

Reputation: 147

I have the solution. This solution I never saw in this blog or any other. I hope it is useful for others.

package Main;

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;

public class XmlTest
{

    public static void main(String argv[]) 
    {

        try 
        {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new File("xmlPrueba.xml"));
            doc.getDocumentElement().normalize();



            System.out.println("City: " +
                    documento.getDocumentElement().getChildNodes().item(0).getFirstChild().getChildNodes().item(0).getAttributes().getNamedItem("data").getNodeValue());

            System.out.println("Postal Code: " +
                    documento.getDocumentElement().getChildNodes().item(0).getFirstChild().getChildNodes().item(1).getAttributes().getNamedItem("data").getNodeValue());

            System.out.println("Date: " +
                    documento.getDocumentElement().getChildNodes().item(0).getFirstChild().getChildNodes().item(4).getAttributes().getNamedItem("data").getNodeValue());

        } catch (Exception e) 
        {
            e.printStackTrace();
        }

    }
}

or more easy ......

            System.out.println("City: " +
                doc.getDocumentElement().getElementsByTagName("forecast_information").item(0).getChildNodes().item(0).getAttributes().getNamedItem("data").getNodeValue());

            System.out.println("Postal Code: " +
                doc.getDocumentElement().getElementsByTagName("forecast_information").item(0).getChildNodes().item(1).getAttributes().getNamedItem("data").getNodeValue());

            System.out.println("Date: " +
                doc.getDocumentElement().getElementsByTagName("forecast_information").item(0).getChildNodes().item(4).getAttributes().getNamedItem("data").getNodeValue());

.....

Thanks for the help!!!

Upvotes: 9

rogue lad
rogue lad

Reputation: 2452

DOM and SAX, both are low level APIs , It's hard to work with them. This question is about

XML Parsing in java

So this can be achieved by SAX and DOM but using Apache Digester will be more easy. This is also known as Data Binding.

Hope this will help you out.

Upvotes: 1

kostja
kostja

Reputation: 61578

Java has several features for XML parsing on board - the SAX, StAX and DOM APIs. The DOM API is the most comfortable one for beginners. Take a look at this nice tutorial.

I must contradict Thom here on XSLT. While being a powerful API, it is rather complex and may be intimidating and frustrating for beginners.

Upvotes: 2

kinaesthesia
kinaesthesia

Reputation: 703

You should look at this :

JDOM : http://www.javaworld.com/jw-05-2000/jw-0518-jdom.html

and

SAX : http://en.wikipedia.org/wiki/Simple_API_for_XML

Simple parser for Java XML

Upvotes: 1

Thom
Thom

Reputation: 15092

Look up XSLT. I've never used it, but it does formatting of XML documents.

Upvotes: 0

Related Questions