How do i get data in XML tags?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   ramanujam_ragavan
Posted On:   Wednesday, July 17, 2002 04:34 AM

I need to do some work with data coming in from an XML file.Someone else is handing me over the elements. I want to get the data that are present within these tags and do something. Can someone tell me how to get the data contained within tags and how to retrieve them. I am dead new to XML and XML Parsing using Java

If you can provide some smple source code i will be grateful.


Thanks in advance

Re: How do i get data in XML tags?

Posted By:   Suhanthan_Vanniyasingam  
Posted On:   Wednesday, July 17, 2002 08:57 PM

Here is a simple example


Save the following files as "MyParser.java" and "sample.xml" respectively. Then compile the java source and run sample.xml as the command line argument. (java MyParser sample.xml). You need to have Xerces to compile these code.



// Simple DOM example MyPaser.java

// Suhanthan Vanniyasingam




import javax.xml.parsers.*;

import org.w3c.dom.*;

import org.xml.sax.*;




public class MyParser

{

 public static void main (String argv[]) throws Exception

 {

  Document doc = null;

  DocumentBuilder builder =
  DocumentBuilderFactory.newInstance().newDocumentBuilder();

  doc = builder.parse (new InputSource (argv[0]));




  if (doc != null)

  {

   Element documentElement = doc.getDocumentElement();

   NodeList nl = documentElement.getChildNodes();

   for (int i=0; i
   {

    Node n = nl.item (i);

    if (n.getNodeType() == n.ELEMENT_NODE)

     printAddress ((Element) n);

   }

  }

 }




 private static void printAddress (Element address)

 {

  NodeList nl = address.getChildNodes();

  for (int i=0; i
  {

   Node n = nl.item (i);

   if (n.getNodeType() == n.ELEMENT_NODE)

   {

    Element el = (Element)n;

    if (el.getTagName().equals("name"))

     System.out.println ("
Name: "+n.getFirstChild().getNodeValue());

    else if (el.getTagName().equals("home"))

     System.out.print ("Address: "+n.getFirstChild().getNodeValue());

   }

  }

 }

}









 



  Suhanthan Vanniyasingam

  54, Green Lane, Colombo 13, Sri Lanka.

 


About | Sitemap | Contact