Results 1 to 7 of 7

Thread: Reading XML

  1. #1
    JSN1 is offline Member
    Join Date
    May 2012
    Posts
    6
    Rep Power
    0

    Exclamation Reading XML

    Hi everyone.

    I'm trying to read a XML file to my program, however, the XML files contains data in a strange way.

    Java Code:
    ther module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
            <forecast_information>
                <city data="Mexico City, Distrito Federal"/>
                <postal_code data="mexico city"/>
                <latitude_e6 data=""/>
                <longitude_e6 data=""/>
                <forecast_date data="2012-05-15"/>
                <current_date_time data="2012-05-15 19:50:00 +0000"/>
                <unit_system data="US"/>
            </forecast_information>
            <current_conditions>
                <condition data="Mostly Cloudy"/>
                <temp_f data="77"/>
                <temp_c data="25"/>
                <humidity data="Humidity: 22%"/>
                <icon data="/ig/images/weather/mostly_cloudy.gif"/>
                <wind_condition data="Wind: N at 12 mph"/>
            </current_conditions>
    The data to read is next to the tag... How can I read that information?

    I'm currently using the next method:

    Java Code:
    public class readxml {
     
    	long Megabyte = 1048576;
    	long Gigabyte = 1073741824;
     
    	public static void main(String[] args) {
    		/**
    		 * Lee un archivo XML de la Memory Stic
    		 */
    		readXML("books.xml");
    	}
     
    	public static void readXML(String path){
    		try{
    			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    			File f = new File(path);
    			Document documento = builder.parse(f);
    			recorrerRamaDOM(documento);
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
     
    	public static void recorrerRamaDOM(Node nodo){
    		if(nodo != null){
    			System.out.println("Nombre del Nodo: " + nodo.getNodeName());
    			System.out.println("Valor del Nodo: " + nodo.getNodeValue());
    			NodeList hijos = nodo.getChildNodes();
    			for(int i = 0; i < hijos.getLength(); i++){
    				Node nodoNieto = hijos.item(i);
    				recorrerRamaDOM(nodoNieto);
    			}
    		}
    	}
    }
    Hope you could help.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Reading XML

    You are wanting to extract the *attributes* of your nodes, and the Node class in fact has methods to help you do this, including hasAttributes(), getAttributes(), ...

    Other ways to consider for extracting this information include XPath and JAXB, the latter is especially useful if you want to make objects from the information extracted.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: Reading XML

    Moved from New to Java

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    JSN1 is offline Member
    Join Date
    May 2012
    Posts
    6
    Rep Power
    0

    Default Re: Reading XML

    Not getting to anything...

    Using this...

    However, I'm unable to do anything with the data.

    Everytime this runs, my vars just go away.



    Java Code:
    package clima;
    
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.XMLFilterImpl;
    
    
    public class UsingJAXPTest1 {
    
        public static void main (String args[]) {
    
    
        
            FileInputStream instream = null;
            InputSource is=null;
    	try {
    	    SAXParserFactory spf = SAXParserFactory.newInstance();
    	    spf.setNamespaceAware(true);
    	    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    
    	    xmlReader.setContentHandler(new MyContentHandler());
    
                instream = new FileInputStream("books.xml");
                is = new InputSource(instream);
    
    	    xmlReader.parse(is);
    	} catch( IOException e) {
    	    e.printStackTrace();
    	    System.exit(0);
    	} catch( SAXException e) {
    	    e.printStackTrace();
    	    System.exit(0);
    	} catch( ParserConfigurationException e) {
    	    e.printStackTrace();
    	    System.exit(0);
    	}
    
        }
    }
    class MyContentHandler extends XMLFilterImpl {
        int contador=0;
    
        public void startElement(String namespaceURI, String localName,
            String qName, Attributes attributes) 
    
        {
            
    
                    if (
               
               localName.equals("city") ||
               localName.equals("postal_code") ||
               localName.equals("forecast_date") ||
               localName.equals("current_date_time") ||
               localName.equals("condition") ||
               localName.equals("low") ||
               localName.equals("high") ||
               localName.equals("icon") ||
               localName.equals("temp_c")) 
            
            {
               String lectura = attributes.getValue("data");
               contador++;
               
               System.out.println(contador + " " + localName+" "+lectura);
            }
    
    
    
          
        }
        
        
    
        
    }

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,802
    Rep Power
    19

    Default Re: Reading XML

    Debug it.
    Stick some println()s into the startElement method, for instance printing out the 'localName', 'namespace', 'qname' and 'attributes'.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    JSN1 is offline Member
    Join Date
    May 2012
    Posts
    6
    Rep Power
    0

    Default Re: Reading XML

    Great. Got it to work.

    Now, I need to read multiple XML files, is that possible?

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Reading Lines
    By gkoef in forum New To Java
    Replies: 6
    Last Post: 04-19-2011, 11:08 PM
  2. Reading numbers
    By edprog in forum New To Java
    Replies: 10
    Last Post: 04-16-2011, 07:17 AM
  3. Reading log
    By Darth Blue Ray in forum New To Java
    Replies: 1
    Last Post: 03-15-2011, 09:35 PM
  4. reading from a .txt
    By Flamespewer in forum New To Java
    Replies: 1
    Last Post: 09-14-2009, 08:35 AM
  5. Replies: 5
    Last Post: 08-21-2009, 11:03 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •