Solved

reading values from XML document

Posted on 2001-06-15
7
210 Views
Last Modified: 2010-03-31
Hi there,
I am new to XML and my java program needs to read the values
from an XML document.
I need to
read specific values and store those values in variables.

Here is the XML Document :

  <?xml version="1.0" encoding="utf-8" ?>
- <smsmessages>
- <header>
  <nbrmsg>2</nbrmsg>
  <error />
- <content>
- <SMS>
  <SERVICE>KULA</SERVICE>
  <GSM>9874983274</GSM>
  <MSG>khjkkj</MSG>
  </SMS>
- <SMS>
  <SERVICE>KULA</SERVICE>
  <GSM>9874983274</GSM>
  <MSG>khjkkj</MSG>
  </SMS>
  </content>
  </header>
  </smsmessages>


Here is the code so far.. I have already got the whole XML document in the variable "xmlDATA" :

      String xmlDATA;
      int nrMSG = 0;
      sms _sms = new sms();
      xmlDATA = _sms.readXMLDocument(URL);

       // First I need to read this value  "<nbrmsg>2</nbrmsg>" to see how many times I have to loop in the for loop.
     
      for (int i=0; i < nrMSG; i++)
       {
        String gsmnumber;
        String msg;
         // here I need get each sms and put it into a variable
       }
0
Comment
Question by:yngvi
7 Comments
 
LVL 5

Expert Comment

by:Calron
ID: 6194792
Sun has some ready made classes that can handle XML files. I would suggest that you use one of those. Have a look at
http://java.sun.com/xml/tutorial_intro.html

for an introduction to one of those tools.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 6195472
Or use something like nanoXML http://nanoxml.sourceforge.net

Tim
0
 
LVL 15

Accepted Solution

by:
ozymandias earned 200 total points
ID: 6195788
Here's an example :

import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.apache.xml.serialize.*;
import java.io.*;

public class XmlTest{

     public static void main(String args[]){

          if (args.length < 2){
               System.out.println("Usage : java XmlTest xmlfile tagname");
               System.exit(1);
          }

          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          try {
               DocumentBuilder builder = factory.newDocumentBuilder();
               Document document = builder.parse(args[0]);
               Element e = document.getDocumentElement();
               NodeList nl = e.getElementsByTagName(args[1]);
               Node n1;
               Node n2;
               for (int i = 0; i < nl.getLength(); i++){
                    n1 = nl.item(i);
                    n2 = n1.getFirstChild();
                    System.out.println(args[1] + " = " + n2.getNodeValue());
               }
          }catch (Exception e) {
               e.printStackTrace();
          }
     }
}
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 15

Expert Comment

by:ozymandias
ID: 6195807
You need to compile this and create an xml file to pass in as the first agument.
Here's the file I used :


<?xml version="1.0" encoding="utf-8" ?>
<smsmessages>
<header>
<nbrmsg>2</nbrmsg>
<error/>
<content>
<SMS>
<SERVICE>KULA</SERVICE>
<GSM>9874983274</GSM>
<MSG>khjkkj</MSG>
</SMS>
<SMS>
<SERVICE>KULA</SERVICE>
<GSM>9874983274</GSM>
<MSG>khjkkj</MSG>
</SMS>
</content>
</header>
</smsmessages>

Once done you can run it like so :

   java XmlTest xmlfile nbrmsg

Basically it creates an xml document and then gets a list of all the elements with the name "nbrmsg". It then gets the first TextElement child of each of the "nbrmsg" elements and prints out its value.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 6195934
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;

public class XEFind{

     public static void main(String args[]){

          if (args.length < 2){
               System.out.println("Usage : java XEFind xmlfile tagname");
               System.exit(1);
          }

          File f = new File(args[0]);
          if (f.exists() && f.canRead()){
               XMLElementFinder xef = new XMLElementFinder(f);
               String s = xef.find(args[1]);
               if (s != null){
                    System.out.println("Element " + args[1] + " found in " + args[0] + ".");
                    System.out.println("Value = " + s);
               }else{
                    System.out.println("No Element " + args[1] + " found in " + args[0] + ".");
               }
          }else{
               System.out.println(args[0] + " either cannot be found or cannot be read.");
          }
     }
}

class XMLElementFinder{

     DocumentBuilderFactory factory;
     DocumentBuilder builder;
     Document document;
     NodeList nl;
     Node n1, n2;

     public XMLElementFinder(File xml){
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          try{
               builder = factory.newDocumentBuilder();
               document = builder.parse(xml);
          }catch (Exception e) {
               e.printStackTrace();
          }
     }

     public String find(String tagName){
          nl = document.getElementsByTagName(tagName);
          if (nl.getLength() > 0){
               n1 = nl.item(0);
               n2 = n1.getFirstChild();
               return n2.getNodeValue();
          }else{
               return null;
          }
     }
}
0
 

Expert Comment

by:CleanupPing
ID: 9062041
yngvi:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 9253894
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:


[points to ozymandias]


Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
sudhakar_koundinya
EE Cleanup Volunteer
---------------------
If you feel that your question was not properly addressed, or that none of the comments received were appropriate answers, please post your concern in THIS thread.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Problem to start Neon 20 87
how do i compare an object based on two fields 6 49
Spring Framework HTTPSession management 1 23
web services creation SOAP vs REST 5 20
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now