Solved

Urgent! Java XML parser...

Posted on 2000-05-08
18
376 Views
Last Modified: 2013-11-23
I NEED big time help on this. I need the source code for a jav program that converts an XML file into objects. We are currently using sun JAVA XML parser API which has DOM/SAX implementation. Preferably I need source code which which does the above and then a another program can read the objects and print them.

example:-
XML--> java parser --> objects containing the XML data --> print on screen.

It should print it such that it shows the variable and then its value. Anyone who has inclination to do this can email me at chaoswarlord50@yahoo.com

urgent!!
0
Comment
Question by:chaos50
  • 8
  • 3
  • 2
  • +5
18 Comments
 
LVL 3

Expert Comment

by:ovidiucraciun
Comment Utility
well ... ;)
0
 
LVL 1

Expert Comment

by:techtime
Comment Utility
I am not sure if it will help you, but here is a link to a very small XML parser that I guess suits you needs just fine.
http://nanoxml.sourceforge.net/nanoxml.zip
I don't understand exactly what you mean by "shows variable and then its value" but what their example application does is very simular.
If you need any customization you can contact me at techtime@rostkl.rnd.su
0
 

Author Comment

by:chaos50
Comment Utility
What I mean is...
when the parser finishes its process...
it then creates classes which hold the xml data right...
This class file is then passed to another java program through invocation which then usses the created classes.
In exact flow:-
a simple display program will invoke the Java parser with an XML as an argument, which then returns the class file to the display program. This program then simply displays the contents of the class file by showing
the a variable in the class and the data which it holds. As an example, lets say the XML has this statement:

<Name>Myname</Name>

The parser would create a class holding variables, one of which is Name and has the value Myname.

Thanks for the 'smile' ovidiucraciun, but I'm wonderring what is so... 'well'.

0
 
LVL 1

Expert Comment

by:yanchou
Comment Utility
Do you want your work done by someone here or you want a advice? There might be different solutation depends on the XML structure...
0
 

Author Comment

by:chaos50
Comment Utility
HOLD on a sec, anyone.... My PC got pooch screwed by some punk's virus. I'm gonna ...

Hopefully I'll be able to put up something this monday. I have a sample code to show what I have vs want I wanted to do...
0
 

Author Comment

by:chaos50
Comment Utility
Sorry for that last one, I don't know java too well and have to complete this by end of next week. There still a lot to do and learn so If possible any sample code would really be appreciated. I you really need to know, I have basic C knowledge but that about it. I'm just a graphic designer/animator!!! How I landed in this job was practically a nightmare.
They said all that was needed was a *litle* programming knowledge....
Sure, right........
0
 
LVL 1

Expert Comment

by:yanchou
Comment Utility
Ummmmm..., Let me show you an example I did before, I hope that will help you out.

Note*: I deleted some information which might be confidential, but I am sure it should be no problem for you to run it.

-------------------------------
1. XML file to be parsed:

<?xml version="1.0" standalone="no"?>
<request id="32880" type="Trouble Ticket Entry Request">
        <header>
                <sender>
                        <key>
                                <login/>
                                <password/>
                                <businessid/>
                        </key>
        </header>
        <body>
                <subrequest id="3456" type="Trouble Ticket Entry">
                </subrequest>
        </body>
</request>

---------------------------------
2. The Java class for this XML:


public class UniqueID{
 public     String ID="";
 public     String ispID="";
 public     String type="";

     public  UniqueID(){}

     public  UniqueID( String ispID,String ID,String type){
        this.ID = ID;
        this.ispID = ispID;
        this.type = type;
     }

     public String toString(){
        return ispID + "_" + ID;
     }
}


------------------------------
Code to parse the xml and extract the information for UniqueID


import java.util.Properties;
import java.io.*;
import org.xml.sax.HandlerBase;
import org.xml.sax.AttributeList;
import org.xml.sax.helpers.ParserFactory;
import org.xml.sax.*;
import com.sun.xml.parser.*;


public class XMLInfo{

    private org.xml.sax.Parser parser = null;

    private static String responseId;

public static Object parse(String XMLContent) {

         UniqueID key = new UniqueID();

         try{
             parser = ParserFactory.makeParser("com.sun.xml.parser.Parser");
             parser.setDocumentHandler(new KeyParser(key));
             StringReader sReader = new StringReader(XMLContent);
             InputSource input = new InputSource(sReader);
             parser.parse(input);
         } catch (SAXParseException e){

             System.out.println ("** Parsing error" + ", line " + e.getLineNumber ()
                                + ", uri " + e.getSystemId ());
             System.out.println("\n" + e.getMessage ());
             

          }
          return key;
     }
}

class KeyParser extends HandlerBase implements Serializable{

      private UniqueID key;
      private String tag="";

      public KeyParser(UniqueID key){
             this.key = key;
      }


public void startElement(String name, AttributeList attrs) throws SAXException{

    tag = name;
    if(tag.equalsIgnoreCase("request")||tag.equalsIgnoreCase("response")){
         key.ID = attrs.getValue("id");
         if (key.ID == null) key.ID ="";
    }

    if(tag.equalsIgnoreCase("subrequest")||tag.equalsIgnoreCase("subresponse")){
         key.type = attrs.getValue("type");
         if (key.type == null) key.type ="";
    }

}


public void endElement(String name) throws SAXException{
    tag = "";
}


public void characters(char buf[], int offset, int len) throws SAXException{
     if (tag.equalsIgnoreCase("login")){
        String value = new String(buf,offset,len) ;
        if (value!=null) key.ispID = value.trim();

     }

}

}






0
 

Author Comment

by:chaos50
Comment Utility
One slight problem, I have this problem:-
----------------------------------------
C:\heve>javac -classpath c:\heve UniqueID.java

C:\heve>pause
Press any key to continue . . .

C:\heve>javac -classpath c:\heve;parser.jar XMLInfo.java
XMLInfo.java:23: Can't make a static reference to nonstatic variable parser in c
lass XMLInfo.
             parser = ParserFactory.makeParser("com.sun.xml.parser.Parser");
             ^
1 error
----------------------------------------
I then added to the problem by adding static to the required line and..
C:\heve>javac -classpath c:\heve;parser.jar XMLInfo.java
XMLInfo.java:22: Exception java.lang.InstantiationException must be caught, or i
t must be declared in the throws clause of this method.
             parser = ParserFactory.makeParser("com.sun.xml.parser.Parser");
                                              ^
XMLInfo.java:22: Exception java.lang.ClassNotFoundException must be caught, or i
t must be declared in the throws clause of this method.
             parser = ParserFactory.makeParser("com.sun.xml.parser.Parser");
                                              ^
XMLInfo.java:22: Exception java.lang.IllegalAccessException must be caught, or i
t must be declared in the throws clause of this method.
             parser = ParserFactory.makeParser("com.sun.xml.parser.Parser");
                                              ^
XMLInfo.java:26: Exception java.io.IOException must be caught, or it must be dec
lared in the throws clause of this method.
             parser.parse(input);
                         ^
XMLInfo.java:26: Exception org.xml.sax.SAXException must be caught, or it must b
e declared in the throws clause of this method.
             parser.parse(input);
                         ^
5 errors
----------------------------------------
help me ok, I new java, 1 week learning.
0
 
LVL 1

Expert Comment

by:yanchou
Comment Utility
in XMLInfo class, please change this line to

1.  
private org.xml.sax.Parser parser = null;

private static org.xml.sax.Parser parser = null;

2. change this line

} catch (SAXParseException e){

as

} catch (Exception e){            

sorry for inconvenient, try this out.

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:chaos50
Comment Utility
Here's another set of problem after the changes.

a) It appears that the Exception class does not posses these methods.

C:\heve>javac -classpath c:\heve;parser.jar XMLInfo.java
XMLInfo.java:30: Invalid expression statement.
                                + ", uri " + e.getSystemId ());
                                           ^
XMLInfo.java:30: ';' expected.
                                + ", uri " + e.getSystemId ());
                                                             ^
2 errors

b)Next, I comented out those lines so that the exception is ignored, with proper adjustments. And got this...
OK, it compiles: but theres no main.
How do I put a main in there. How would the main call the parser 'object'. I don't understand that part. I have been reading books, but most of them show the use of main differently and I not quite sure of how to implement that, here.

Anyway, I tried by replacing the 'Object parser' with 'void main' becasue most of te other program does that. Obviously it doesn't work. I was thinking about a program which receives a XML file as an argument, then executes the parsing based on that file.

Hows about your email, that would make it easier for me to send the files which I've altered and let you decide.?
Again my email is chaoswarlord50@yahoo.com .

0
 
LVL 1

Expert Comment

by:karthicraja
Comment Utility
HOPE THIS HELPS
KARTHIC

EXAMPLE.
 
<?xml version="1.0" encoding="UTF-8"?>
<rulefile>
      <field name="page">
            <start>images/rightarrow.gif</start>
            <end>Show next</end>
      </field>
      <field name="url">
            <start>Position Title:</start>
            <end>&gt;</end>
      </field>
      <field Name="nextpage">
            <start>images/rightarrow.gif</start>
            <end>Show next</end>
      </field>
</rulefile>


// THIS CODE WILL GIVE YOU AN IDEA ABOUT HOW TO PROCEED IN, NOT THE EXACT SOLUTION FOR YOUR QUESTION


public class XMLExtractor
{

    private Hashtable fields = new Hashtable();

    private XMLDocument doc;

    public XMLExtractor()
    {
        fields = new Hashtable();
    }
   
    public void configureSettings(String pstrFileName) throws Exception
    {

        DOMParser parser = new DOMParser();
       
        URL url = URLCreator.getURL(pstrFileName); // given the file name gives you the URL like file:/d:/abc.xml

        parser.setErrorStream(System.err);

        parser.setValidationMode(false);
       
        parser.showWarnings(true);

        parser.parse(url);

        doc = parser.getDocument();
    }

    public void validate(Object obj)
    {
        if(obj == null)
        {
            System.out.println("Initialisation of XML object failure");
           
            System.exit(0);
        }
    }

    // THIS FUNCTION EXTRACTS THE FIELDS IN THE ABOVE XML IT IS "field" TAG


    public void getElements(String tagName)
    {

        NodeList list = doc.getElementsByTagName(tagName);
       
        int len = list.getLength();
       
        for (int i=0; i < len; i++)
        {

            Element e = (Element)list.item(i);

            NamedNodeMap nodeMap = e.getAttributes();

            if (nodeMap != null)
            {

                for (int j=0; j<nodeMap.getLength(); j++)
                {

                    Node n = nodeMap.item(j);

                    String  attName = n.getNodeValue();

                    fields.put(attName,e);

                }
            }
        }
    }

    // THIS FUNCTION EXTRACTS THE ATTRIBUTES. LIKE HERE IN THE XML, IMAGES\RIGHTARROW.GIF

    public SearchTag getValue(String pstrAttribute)
    {

        // THIS IS THE OBJECT WHERE YOU ARE GOING TO STORE YOUR VALUES, IT ALL DEPENDS ON YOU TO FRAME THIS.

        SearchTag stag = new SearchTag();
       
        Element e = (Element) fields.get(pstrAttribute);

        validate(e);

        NodeList list = e.getChildNodes();
       
        if(list != null)
        {
            stag.setLength( list.getLength()-1);

            for(int i=0;i<list.getLength(); i++)
            {
                NodeList n2 = list.item(i).getChildNodes();

                if(n2 != null)
                {
                    if(list.item(i).getNodeName().compareToIgnoreCase("start") == 0)
                    {
                        stag.setStartTag( n2.item(0).getNodeValue() );
                    }
                   
                    else
                       
                        stag.setEndTag( n2.item(0).getNodeValue() );
                }
            }
        }
        return stag;
    }

    static public void main(String[] argv)
    {
        try
        {
            Hashtable fields = new Hashtable();
           
            XMLExtractor a = new XMLExtractor();
           
            a.configureSettings("123.xml");
           
            a.getElements("fields");
           
            a.getValue("page");
           
            a.getValue("url");
           
            a.getValue("nextpage");
           
        }
        catch (Exception e)
        {
           
            System.out.println(e.toString());
           
        }
    }
}



0
 
LVL 1

Accepted Solution

by:
techtime earned 350 total points
Comment Utility
I've emailed my code to you chaos50.
0
 

Author Comment

by:chaos50
Comment Utility
Sorry, But techtime has helped me way more. He deserves it.
0
 

Author Comment

by:chaos50
Comment Utility
Comment accepted as answer
0
 

Author Comment

by:chaos50
Comment Utility
No comment needed. It's all said and done. Thanks.
0
 

Expert Comment

by:funksoul
Comment Utility
techtime or chaos50

Can you email the code as well....I have a similar task to be performed.

thanks!

tym1@hotmail.com
0
 

Expert Comment

by:spetrowitsch
Comment Utility
techtime, chaos50 or funksoul,


Can you email the code as well....I have a similar task to be performed.

thanks!

s.petrowitsch@ce-datronic.com
0
 
LVL 8

Expert Comment

by:Subrat (C++ windows/Linux)
Comment Utility
hello Everyone(techtime, chaos50 or funksoul,s.petrowitsch@ce-datronic.com),
Can u plz email the same to me by which i'll use it and also keep it here by which no one else who is having same problem, won't tell us to e-mail:).
subrat.net@gmail.com
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

762 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

12 Experts available now in Live!

Get 1:1 Help Now