Parsing XML with Java - seeking advice for method to pursue

Hi guys
So here's the deal: I want to parse some XML from a server, get all the data I need from it, then shunt that data to the classes that need it. However, I'm really not sure what the best way of parsing the XML is.
I've just written a class for obtaining the file, and one for building a DOM from the XML file. But looking at org.w3c.dom in the Java API documentation (see HERE) I'll have to implement shedloads of interfaces to be able to take advantage of the DOM, and I don't even know a lot about it.
So am I best just writing a simple parser based on regular expressions to get the data I want? There's about 5 attributes in the XML file that I need to get - 5 for each instance of the containing element. So I don't think it'll be hard to do with regular expressions.. plus even if I did decide to implement all the DOM interfaces, the only way I'd know how to do half the stuff is with regular expressions anyway. I mean, how else would you do it? How else could you match up Nodes according to the Strings you're using for the elements, attributes etc?
I worry that a parser using regular expressions might be too slow... I'm building this as an applet to visually display information from the server. I have nothing to support those fears, I'm just not experienced enough to know whether speed would be a problem if I chose this route... I don't think it would, but really need confirmation of that suspicion being unfounded.
Any advice would be very, very welcome, as I'm tearing my hair out at the moment, unsure what to do.

Komodo wrote:But JDOM is not in the core class libraries, is it? So if I want to create an applet embedded into a website, am I able to get people to download that as well?
Sorry, I don't know anything about applets.
Komodo wrote:Everyone's advice is appreciated, but my core question remains unanswered - would using regular expressions, considering how simple and unchanging the XML files are, be a viable option in terms of speed?
Yes! I've done more than my fair share of XML processing with REs. It's not always easy. I often wish I could just use something XPath-like. But it's certainly easy to do and would probably mean that you'd have something up and running quicker than if you spent time investigating pure XML parsing approaches.

Similar Messages

  • How to parse XML to Java object... please help really stuck

    Thank you for reading this email...
    If I have a **DTD** like:
    <!ELEMENT person (name, age)>
    <!ATTLIST person
         id ID #REQUIRED
    >
    <!ELEMENT name ((family, given) | (given, family))>
    <!ELEMENT age (#PCDATA)>
    <!ELEMENT family (#PCDATA)>
    <!ELEMENT given (#PCDATA)>
    the **XML** like:
    <person id="a1">
    <name>
         <family> Yoshi </family>
         <given> Samurai </given>
    </name>
    <age> 21 </age>
    </person>
    **** Could you help me to write a simple parser to parse my DTD and XML to Java object, and how can I use those objects... sorry if the problem is too basic, I am a beginner and very stuck... I am very confuse with SAXParserFactory, SAXParser, ParserAdapter and DOM has its own Factory and Parser, so confuse...
    Thank you for your help, Yo

    Hi, Yo,
    Thank you very much for your help. And I Wish you are there...I'm. And I plan to stay - It's sunny and warm here in Honolulu and the waves are up :)
    A bit more question for dear people:
    In the notes, it's mainly focus on JAXB,
    1. Is that mean JAXB is most popular parser for
    parsing XML into Java object? With me, definitely. There are essentially 3 technologies that allow you to parse XML documents:
    1) "Callbacks" (e.g. SAX in JAXP): You write a class that overrides 3 methods that will be called i) whenever the parser encounters a start tag, ii) an end tag, or iii) PCDATA. Drawback: You have to figure out where the heck in the document hierarchy you are when such a callback happens, because the same method is called on EACH start tag and similarly for the end tag and the PCDATA. You have to create the objects and put them into your own data structure - it's very tedious, but you have complete control. (Well, more or less.)
    2) "Tree" (e.g. DOM in JAXP, or it's better cousin JDOM): You call a parser that in one swoop creates an entire hierarchy that corresponds to the XML document. You don't get called on each tag as with SAX, you just get the root of the resulting tree. Drawback: All the nodes in the tree have the same type! You probably want to know which tags are in the document, don't you? Well, you'll have to traverse the tree and ask each node: What tag do you represent? And what are your attributes? (You get only strings in response even though your attributes often represent numbers.) Unless you want to display the tree - that's a nice application, you can do it as a tree model for JTree -, or otherwise don't care about the individual tags, DOM is not of much help, because you have to keep track where in the tree you are while you traverse it.
    3) Enter JAXB (or Castor, or ...): You give it a grammar of the XML documents you want to parse, or "unmarshall" as the fashion dictates to call it. (Actually the name isn't that bad, because "parsing" focuses on the input text while "unmarshalling" focuses on the objects you get, even though I'd reason that it should be marshalling that converts into objects and unmarshalling that converts objects to something else, and not vice versa but that's just my opinion.) The JAXB compiler creates a bunch of source files each with one (or now more) class(es) (and now interfaces) that correspond to the elements/tags of your grammar. (Now "compiler" is a true jevel of a misnomer, try to explain to students that after they run the "compiler", they still need to compile the sources the "compiler" generated with the real Java compiler!). Ok, you've got these sources compiled. Now you call one single method, unmarshall() and as a result you get the root node of the hierarchy that corresponds to the XML document. Sounds like DOM, but it's much better - the objects in the resulting tree don't have all the same type, but their type depends on the tag they represent. E.g if there is the tag <ball-game> then there will be an object of type myPackage.BallGame in your data structure. It gets better, if there is <score> inside <ball-game> and you have an object ballGame (of type BallGame) that you can simply call ballGame.getScore() and you get an object of type myPackage.Score. In other words, the child tags become properties of the parent object. Even better, the attributes become properties, too, so as far as your program is concerned there is no difference whether the property value was originally a tag or an attribute. On top of that, you can tell in your schema that the property has an int value - or another primitive type (that's like that in 1.0, in the early release you'll have to do it in the additional xjs file). So this is a very natural way to explore the data structure of the XML document. Of course there are drawbacks, but they are minor: daunting complexity and, as a consequence, very steep learning curve, documentation that leaves much to reader's phantasy - read trial and error - (the user's guide is too simplicistic and the examples too primitive, e.g. they don't even tell you how to make a schema where a tag has only attributes) and reference manual that has ~200 pages full of technicalities and you have to look with magnifying glas for the really usefull stuff, huge number of generated classes, some of which you may not need at all (and in 1.0 the number has doubled because each class has an accompanying interface), etc., etc. But overall, all that pales compared to the drastically improved efficiency of the programmer's efforts, i.e. your time. The time you'll spend learning the intricacies is well spent, you'll learn it once and then it will shorten your programming time all the time you use it. It's like C and Java, Java is order of magnitude more complex, but you'd probably never be sorry you gave up C.
    Of course the above essay leaves out lots and lots of detail, but I think that it touches the most important points.
    A word about JAXB 1.0 vs. Early Release (EA) version. If you have time, definitively learn 1.0, they are quite different and the main advantage is that the schema combines all the info that you had to formulate in the DTD and in the xjs file when using the EA version. I suggested EA was because you had a DTD already, but in retrospect, you better start from scratch with 1.0. The concepts in 1.0 are here to stay and once your surmounted the learning curve, you'll be glad that you don't have to switch concepts.
    When parser job is done,
    what kind of Java Object we will get? (String,
    InputStream or ...)See above, typically it's an object whose type is defined as a class (and interface in 1.0) within the sources that JABX generates. Or it can be a String or one of the primitive types - you tell the "compiler" in the schema (xjs file in EA) what you want!
    2. If we want to use JAXB, we have to contain a
    XJS-file? Something like:In EA, yes. In 1.0 no - it's all in the schema.
    I am very new to XML, is there any simpler way to get
    around them? It has already take me 4 days to find a
    simple parser which give it XML and DTD, then return
    to me Java objects ... I mean if that kind of parser
    exists....It'll take you probably magnitude longer that that to get really familiar with JAXB, but believe me it's worth it. You'll save countless days if not weeks once you'll start developing serious software with it. How long did it take you to learn Java and it's main APIs? You'll either invest the time learning how to use the software others have written, or you invest it writing it yourself. I'll take the former any time. But it's only my opinion...
    Jan

  • Problem parsing XML with schema when extracted from a jar file

    I am having a problem parsing XML with a schema, both of which are extracted from a jar file. I am using using ZipFile to get InputStream objects for the appropriate ZipEntry objects in the jar file. My XML is encrypted so I decrypt it to a temporary file. I am then attempting to parse the temporary file with the schema using DocumentBuilder.parse.
    I get the following exception:
    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element '<root element name>'
    This was all working OK before I jarred everything (i.e. when I was using standalone files, rather than InputStreams retrieved from a jar).
    I have output the retrieved XML to a file and compared it with my original source and they are identical.
    I am baffled because the nature of the exception suggests that the schema has been read and parsed correctly but the XML file is not parsing against the schema.
    Any suggestions?
    The code is as follows:
      public void open(File input) throws IOException, CSLXMLException {
        InputStream schema = ZipFileHandler.getResourceAsStream("<jar file name>", "<schema resource name>");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
          factory.setNamespaceAware(true);
          factory.setValidating(true);
          factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
          factory.setAttribute(JAXP_SCHEMA_SOURCE, schema);
          builder = factory.newDocumentBuilder();
          builder.setErrorHandler(new CSLXMLParseHandler());
        } catch (Exception builderException) {
          throw new CSLXMLException("Error setting up SAX: " + builderException.toString());
        Document document = null;
        try {
          document = builder.parse(input);
        } catch (SAXException parseException) {
          throw new CSLXMLException(parseException.toString());
        }

    I was originally using getSystemResource, which worked fine until I jarred the application. The problem appears to be that resources returned from a jar file cannot be used in the same way as resources returned directly from the file system. You have to use the ZipFile class (or its JarFile subclass) to locate the ZipEntry in the jar file and then use ZipFile.getInputStream(ZipEntry) to convert this to an InputStream. I have seen example code where an InputStream is used for the JAXP_SCHEMA_SOURCE attribute but, for some reason, this did not work with the InputStream returned by ZipFile.getInputStream. Like you, I have also seen examples that use a URL but they appear to be URL's that point to a file not URL's that point to an entry in a jar file.
    Maybe there is another way around this but writing to a file works and I set use File.deleteOnExit() to ensure things are tidied afterwards.

  • Starting xml with java

    hi all,
    cud any one provide me with the url that contain the examples of how to integrate xml with java.as i am new in this field so i need something from the very basic.and what all stuff do i need on my system to run the code.
    thanx in advance
    anshul

    http://java.sun.com/xml/index.html

  • How to parse xml in java

    i wrote java client to invoke webservice(TIBCO) as a result i am getting back xml. now i have to parse xml and use the information. can anyone pls advise on this.
    thanks

    There are two kinds of parser available. One converts the XML to a Document Object Model (DOM). This is a heirarchy of Node objects each of which represents an element of XML, a tag, an attribute a piece of text etc.. Then you walk the graph extracting what you want.
    The other kind is the SAX event parser. You give this a callback (extends DefaultHandler) and it calls appropriate methods for each element as it's encountered.
    The second method is probably slight more complex to use but will deal with files of unlimited size without huge memory usage.
    In both cases you get the parser using a Factory/Interface pattern. You'll find the factory classes in javax.xml.parsers. The rest of the DOM stuff is in org.w3c.dom and the SAX stuff in org.xml.sax.

  • How to Parse XML with SAX and Retrieving the Information?

    Hiya!
    I have written this code in one of my classes:
    /**Parse XML File**/
              SAXParserFactory factory = SAXParserFactory.newInstance();
              GameContentHandler gameCH = new GameContentHandler();
              try
                   SAXParser saxParser = factory.newSAXParser();
                   saxParser.parse(recentFiles[0], gameCH);
              catch(javax.xml.parsers.ParserConfigurationException e)
                   e.printStackTrace();
              catch(java.io.IOException e)
                   e.printStackTrace();
              catch(org.xml.sax.SAXException e)
                   e.printStackTrace();
              /**Parse XML File**/
              games = gameCH.getGames();And here is the content handler:
    import java.util.ArrayList;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    class GameContentHandler extends DefaultHandler
         private ArrayList<Game> games = new ArrayList<Game>();
         public void startDocument()
              System.out.println("Start document.");
         public void endDocument()
              System.out.println("End document.");
         public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
         public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
         public void characters(char[] ch, int start, int length) throws SAXException
              /**for (int i = start; i < start+length; i++)
                   System.out.print(ch);
         public ArrayList<Game> getGames()
              return games;
    }And here is the xml i am trying to parse:<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
    <Database>
         <Name></Name>
         <Description></Description>
         <CurrentGameID></CurrentGameID>
         <Game>
              <gameID></gameID>
              <name></name>
              <publisher></publisher>
              <platform></platform>
              <type></type>
              <subtype></subtype>
              <genre></genre>
              <serial></serial>
              <prodReg></prodReg>
              <expantionFor></expantionFor>
              <relYear></relYear>
              <expantion></expantion>
              <picPath></picPath>
              <notes></notes>
              <discType></discType>
              <owner></owner>
              <location></location>
              <borrower></borrower>
              <numDiscs></numDiscs>
              <discSize></discSize>
              <locFrom></locFrom>
              <locTo></locTo>
              <onLoan></onLoan>
              <borrowed></borrowed>
              <manual></manual>
              <update></update>
              <mods></mods>
              <guide></guide>
              <walkthrough></walkthrough>
              <cheats></cheats>
              <savegame></savegame>
              <completed></completed>
         </Game>
    </Database>I have been trying for ages and just can't get the content handler class to extract a gameID and instantiate a Game to add to my ArrayList! How do I extract the information from my file?
    I have tried so many things in the startElement() method that I can't actually remember what I've tried and what I haven't! If you need to know, the Game class instantiates with asnew Game(int gameID)and the rest of the variables are public.
    Please help someone...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    OK, how's this?
    public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
              current = "";
         public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
              try
                   if(qualifiedName.equals("Game") || qualifiedName.equals("Database"))
                        {return;}
                   else if(qualifiedName.equals("gameID"))
                        {games.add(new Game(Integer.parseInt(current)));}
                   else if(qualifiedName.equals("name"))
                        {games.get(games.size()-1).name = current;}
                   else if(qualifiedName.equals("publisher"))
                        {games.get(games.size()-1).publisher = current;}
                   etc...
                   else
                        {System.out.println("ERROR - Qualified Name found in xml that does not exist as databse field: " + qualifiedName);}
              catch (Exception e) {} //Ignore
         public void characters(char[] ch, int start, int length) throws SAXException
              current += new String(ch, start, length);
         }

  • Parsing XML using java DOM

    hi
    i am trying to parse a document and change a specific text value within an element althouh when i run the program it changes the nodes text however when i check the xml file it doesnt show the changes it remains the same the code that i am using is as follow iwould be greatful if any one culd help:
    //  ReplaceText.java
    // Reads intro.xml and replaces a text node.
    // Java core packages
    import java.io.*;
    // Java extension packages
    import javax.xml.parsers.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import javax.xml.transform.dom.*;
    // third-party libraries
    import org.xml.sax.*;
    import org.w3c.dom.*;
    public class ReplaceText {
       private Document document;
       public ReplaceText()
          // parse document, find/replace element, output result
          try {
             // obtain default parser
             DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
             // set parser as validating          
             factory.setValidating( true );
             // obtain object that builds Documents
             DocumentBuilder builder = factory.newDocumentBuilder();
             // set error handler for validation errors
             builder.setErrorHandler( new MyErrorHandler() );
      System.err.println( "reading" );
             // obtain document object from XML document
             File f = new File("D:/Documents and Settings/Administrator/Desktop/xml adv java bk/appC/intro.xml");
              System.err.println( "reading" );
             document = builder.parse(f);
    //document = builder.parse( new File( "intro.xml" ) );
    System.err.println( "reading document" );
             // retrieve the root node
             Node root = document.getDocumentElement();
             if ( root.getNodeType() == Node.ELEMENT_NODE ) {
                Element myMessageNode = ( Element ) root;
                NodeList messageNodes =
                   myMessageNode.getElementsByTagName( "message5" );
                if ( messageNodes.getLength() != 0 ) {
                   Node message = messageNodes.item( 0 );
                        System.out.println("iiiii");
                   // create text node
                   Text newText = document.createTextNode(
                      "New Changed Message!!" );
                   // get old text node
                   Text oldText =
                      ( Text ) message.getChildNodes().item( 0 ); 
                   // replace text
                   //message.removeChild(oldText);
                   message.replaceChild( newText, oldText );
             // output Document object
             // create DOMSource for source XML document
             Source xmlSource = new DOMSource( document );
             // create StreamResult for transformation result
             Result result = new StreamResult( System.out );
             // create TransformerFactory
             TransformerFactory transformerFactory =
                TransformerFactory.newInstance();
             // create Transformer for transformation
             Transformer transformer =
                transformerFactory.newTransformer();
             transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
               transformer.setOutputProperty( OutputKeys.STANDALONE, "yes" );
             // transform and deliver content to client
             transformer.transform( xmlSource, result );
          // handle exception creating DocumentBuilder
          catch ( ParserConfigurationException parserException ) {
             parserException.printStackTrace();
          // handle exception parsing Document
          catch ( SAXException saxException ) {
             saxException.printStackTrace();        
          // handle exception reading/writing data
          catch ( IOException ioException ) {
             ioException.printStackTrace();
             System.exit( 1 );
          // handle exception creating TransformerFactory
          catch (
             TransformerFactoryConfigurationError factoryError ) {
             System.err.println( "Error while creating " +
                "TransformerFactory" );
             factoryError.printStackTrace();
          // handle exception transforming document
          catch ( TransformerException transformerError ) {
             System.err.println( "Error transforming document" );
             transformerError.printStackTrace();
       public static void main( String args[] )
          ReplaceText replace = new ReplaceText();   
    }the xml file that i am using is as follows:
    <?xml version = "1.0"?>
    <!-- Fig. 28.10 : intro.xml             -->
    <!-- Simple introduction to XML markup   -->
    <!DOCTYPE myMessage [
         <!ELEMENT myMessage (message, message5)>
         <!ELEMENT message (#PCDATA)>
         <!ELEMENT message5 (#PCDATA)>
    ]>
    <myMessage>
         <message>welcome to the xml shhhhhushu</message>
         <message5>welcome to the xml shhhhhushu</message5>
    </myMessage>i would be greatful if some one could please help.....

    See if the Text 'oldText' actually has any text within it. Sometimes in DOM parsing, you will get something like:
    Element
       Text (blank)
       Text (actual)
       Text (blank)Whereas you would expect to receive:
    Element
       Text (actual)See if that is the case. If yes, modify your logic to iterate through the child text nodes until one with actual text inside of it (getNodeValue()) is found.
    - Saish

  • Parsing xml in java program

    In the following code i M NOT able to understand the use of part of code that is in BOLD
    int tableno=tree.getChildCount();
    *for(int table=0;table<tableno;table++){*
    *if(table==0){*
    tree=((DefaultMutableTreeNode)tree.getFirstChild());
    *}else{*
    tree=((DefaultMutableTreeNode)tree.getNextSibling());
    tag1=(Tag)tree.getUserObject();
    tableobj=(Table)tag1.getObject();
    int rowno=tree.getChildCount();
    *for(int rows=0;rows<rowno;rows++){*
    *if(rows==0){*
    tree=((DefaultMutableTreeNode)tree.getFirstChild());
    *}else{*
    tree=((DefaultMutableTreeNode)tree.getNextSibling());
    tag1=(Tag)tree.getUserObject();
    int colno=tree.getChildCount();
    *for(int cols=0;cols<colno;cols++){*
    *if(cols==0){*
    tree=((DefaultMutableTreeNode)tree.getFirstChild());
    *}else{*
    tree=((DefaultMutableTreeNode)tree.getNextSibling());
    tag1=(Tag)tree.getUserObject();
    columnobj=(Column)tag1.getObject();
    int inner=tree.getChildCount();
    *for(int k=0;k<inner;k++){*
    *if(k==0){*
    tree=((DefaultMutableTreeNode)tree.getFirstChild());
    *}else{*
    tree=((DefaultMutableTreeNode)tree.getNextSibling());
    tag1=(Tag)tree.getUserObject();
    *if(tag1.getName().equalsIgnoreCase("image")){*
    imagetag=(Images)tag1.getObject();
    *if(imagetag.getId().equalsIgnoreCase("3")){*
    *if(!lightimage.equals("")) {*
    *     imagetag.setURL(lightimage);*
    *}*

    This is the simplest way to read data from an XML file into a Java program. I have also included some basic error checking, so you can directly cut-paste this code with a few changes ofcourse. All you have to do is change the XML tags within the program to match those that are present in your XML file.
    XML File
    +<book>+
    +<person>+
    +<first>Kiran</first>+
    +<last>Pai</last>+
    +<age>22</age>+
    +</person>+
    +<person>+
    +<first>Bill</first>+
    +<last>Gates</last>+
    +<age>46</age>+
    +</person>+
    +<person>+
    +<first>Steve</first>+
    +<last>Jobs</last>+
    +<age>40</age>+
    +</person>+
    +</book>+
    Java Progarm for Parsing the above XML File:
    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class ReadAndPrintXMLFile{
    public static void main (String argv []){
    try {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("book.xml"));
    // normalize text representation
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " +
    doc.getDocumentElement().getNodeName());
    NodeList listOfPersons = doc.getElementsByTagName("person");
    int totalPersons = listOfPersons.getLength();
    System.out.println("Total no of people : " + totalPersons);
    for(int s=0; s<listOfPersons.getLength() ; s++){
    Node firstPersonNode = listOfPersons.item(s);
    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
    Element firstPersonElement = (Element)firstPersonNode;
    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
    Element firstNameElement = (Element)firstNameList.item(0);
    NodeList textFNList = firstNameElement.getChildNodes();
    System.out.println("First Name : " +
    ((Node)textFNList.item(0)).getNodeValue().trim());
    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
    Element lastNameElement = (Element)lastNameList.item(0);
    NodeList textLNList = lastNameElement.getChildNodes();
    System.out.println("Last Name : " +
    ((Node)textLNList.item(0)).getNodeValue().trim());
    NodeList ageList = firstPersonElement.getElementsByTagName("age");
    Element ageElement = (Element)ageList.item(0);
    NodeList textAgeList = ageElement.getChildNodes();
    System.out.println("Age : " +
    ((Node)textAgeList.item(0)).getNodeValue().trim());
    }//end of if clause
    }//end of for loop with s var
    }catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line "
    + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
    }catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    }catch (Throwable t) {
    t.printStackTrace ();
    //System.exit (0);
    }//end of main
    There are better implementations of reading XML files which would work for any XML file. The above one would require a few changes every time the XML tag names change. But this is much more simpler than the other programs.

  • Persisting unexplained errors when parsing XML with schema validation

    Hi,
    I am trying to parse an XML file including XML schema validation. When I validate my .xml and .xsd in NetBeans 5.5 beta, I get not error. When I parse my XML in Java, I systematically get the following errors no matter what I try:
    i) Document root element "SQL_STATEMENT_LIST", must match DOCTYPE root "null".
    ii) Document is invalid: no grammar found.
    The code I use is the following:
    try {
    Document document;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse( new File(PathToXml) );
    My XML is:
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <!-- Defining the SQL_STATEMENT_LIST element -->
    <xs:element name="SQL_STATEMENT_LIST" type= "SQL_STATEMENT_ITEM"/>
    <xs:complexType name="SQL_STATEMENT_ITEM">
    <xs:sequence>
    <xs:element name="SQL_SCRIPT" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    </xs:complexType>
    <!-- Defining simple type ApplicationType with 3 possible values -->
    <xs:simpleType name="ApplicationType">
    <xs:restriction base="xs:string">
    <xs:enumeration value="DawningStreams"/>
    <xs:enumeration value="BaseResilience"/>
    <xs:enumeration value="BackBone"/>
    </xs:restriction>
    </xs:simpleType>
    <!-- Defining the SQL_SCRIPT element -->
    <xs:element name="SQL_SCRIPT" type= "SQL_STATEMENT"/>
    <xs:complexType name="SQL_STATEMENT">
    <xs:sequence>
    <xs:element name="NAME" type="xs:string"/>
    <xs:element name="TYPE" type="xs:string"/>
    <xs:element name="APPLICATION" type="ApplicationType"/>
    <xs:element name="SCRIPT" type="xs:string"/>
    <!-- Making sure the following element can occurs any number of times -->
    <xs:element name="FOLLOWS" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    </xs:complexType>
    </xs:schema>
    and my XML is:
    <?xml version="1.0" encoding="UTF-8"?>
    <!--
    Document : SQLStatements.xml
    Created on : 1 juillet 2006, 15:08
    Author : J�r�me Verstrynge
    Description:
    Purpose of the document follows.
    -->
    <SQL_STATEMENT_LIST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://www.dawningstreams.com/XML-Schemas/SQLStatements.xsd">
    <SQL_SCRIPT>
    <NAME>CREATE_PEERS_TABLE</NAME>
    <TYPE>CREATION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    CREATE CACHED TABLE PEERS (
    PEER_ID           VARCHAR(20) NOT NULL,
    PEER_KNOWN_AS      VARCHAR(30) DEFAULT ' ' ,
    PRIMARY KEY ( PEER_ID )
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>CREATE_COMMUNITIES_TABLE</NAME>
    <TYPE>CREATION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    CREATE CACHED TABLE COMMUNITIES (
    COMMUNITY_ID VARCHAR(20) NOT NULL,
    COMMUNITY_KNOWN_AS VARCHAR(25) DEFAULT ' ',
    PRIMARY KEY ( COMMUNITY_ID )
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>CREATE_COMMUNITY_MEMBERS_TABLE</NAME>
    <TYPE>CREATION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    CREATE CACHED TABLE COMMUNITY_MEMBERS (
    COMMUNITY_ID VARCHAR(20) NOT NULL,
    PEER_ID VARCHAR(20) NOT NULL,
    PRIMARY KEY ( COMMUNITY_ID, PEER_ID )
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>DROP_PEER_TABLE</NAME>
    <TYPE>DELETION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    DROP TABLE PEERS IF EXISTS
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>DROP_COMMUNITIES_TABLE</NAME>
    <TYPE>DELETION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    DROP TABLE COMMUNITIES IF EXISTS
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>DROP_COMMUNITY_MEMBERS_TABLE</NAME>
    <TYPE>DELETION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    DROP TABLE COMMUNITY_MEMBERS IF EXISTS
    </SCRIPT>
    </SQL_SCRIPT>
    <SQL_SCRIPT>
    <NAME>CREATE_COMMUNITY_MEMBERS_VIEW</NAME>
    <TYPE>CREATION</TYPE>
    <APPLICATION>DawningStreams</APPLICATION>
    <SCRIPT>
    CREATE VIEW COMMUNITY_MEMBERS_VW AS
    SELECT P.PEER_ID, P.PEER_KNOWN_AS, C.COMMUNITY_ID, C.COMMUNITY_KNOWN_AS
    FROM PEERS P, COMMUNITIES C, COMMUNITY_MEMBERS CM
    WHERE P.PEER_ID = CM.PEER_ID
    AND C.COMMUNITY_ID = CM.COMMUNITY_ID
    </SCRIPT>
    <FOLLOWS>CREATE_PEERS_TABLE</FOLLOWS>
    <FOLLOWS>CREATE_COMMUNITIES_TABLE</FOLLOWS>
    </SQL_SCRIPT>
    </SQL_STATEMENT_LIST>
    Any ideas? Thanks !!!
    J�r�me Verstrynge

    Hi,
    I found the solution in the following post:
    Validate xml with DOM - no grammar found
    Sep 17, 2003 10:58 AM
    The solution is to add a line of code when parsing:
    try {
    Document document;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse( new File(PathToXml) );
    The errors are gone !!!
    J�r�me Verstrynge

  • Parsing XML with Namespace

    Hi,
    Can somebody help me with the following:-
    I have an XMLType in pl/sql as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <rapdrpProcessCIN:GetCINRes xmlns:rapdrpProcessCIN="http://rapdrp.com/processcin/transactional/model/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://rapdrp.com/processcin/transactional/model/1.0/"
    xmlns:N1="http://rapdrp.com/common/bodcomponents/transactional/model/1.0/"
    xmlns:N2="http://rapdrp.com/gis/cin/business/model/1.0/">
    <rapdrpProcessCIN:ApplicationArea>
    <N1:Sender>
    <N1:Id>PRT01</N1:Id>
    </N1:Sender>
    <N1:Receiver>
    <N1:CompanyName>MGVCL</N1:CompanyName>
    <N1:CompanyId>string</N1:CompanyId>
    </N1:Receiver>
    <N1:Reference>
    <N1:BODCreationDateTime>1697-02-01T00:00:00Z</N1:BODCreationDateTime>
    <N1:BusinessProcessId>BP014</N1:BusinessProcessId>
    <N1:MessageId>string</N1:MessageId>
    <N1:TransactionId>string</N1:TransactionId>
    <N1:Username>string</N1:Username>
    <N1:Token>string</N1:Token>
    </N1:Reference>
    </rapdrpProcessCIN:ApplicationArea>
    <rapdrpProcessCIN:DataArea>
    <rapdrpProcessCIN:CIN>
    <N2:CIN>string</N2:CIN>
    </rapdrpProcessCIN:CIN>
    <rapdrpProcessCIN:ConsumerNumber>string</rapdrpProcessCIN:ConsumerNumber>
    <rapdrpProcessCIN:SRNumber>string</rapdrpProcessCIN:SRNumber>
    </rapdrpProcessCIN:DataArea>
    </rapdrpProcessCIN:GetCINRes>Note the xmlns attribute of the <message> tag is "" which is unusual, but not something I can't modify.
    I wish to extract the text string of the BusinessProcessId tag. I have attempted the following:
    DECLARE
    v_result varchar2(32765);
    v_xml XMLType;
    BEGIN
    v_xml := XMLType('....above XML....');
    v_result := xmltype.extract(v_xml, '/rapdrpProcessCIN:GetCINRes/rapdrpProcessCIN:ApplicationArea/Reference/BusinessProcessId/text()','xmlns:rapdrpProcessCIN="http://rapdrp.com/processcin/transactional/model/1.0/"').getStringVal();
    dbms_output.put_line('v_result:'||v_result);
    END;
    .... and I'm receiving the following result:
    ORA-30625: method dispatch on NULL SELF argument is disallowed
    ORA-06512: at line 6
    What am I doing wrong?
    Any help appreciated.
    Regards,
    Himani

    Hello,
    Can u please help me in resolving this issue.
    I need to parse an XML in which some tags does not contain data or there is no such tag present in an XML.
    Whenever i parse such a XML i receive error-ORA-30625: method dispatch on NULL SELF Argument is disallowed.
    As per my requirement - I may get values in all tags at one time and next time i may receive values of some fields only.
    I have tried this:
    DECLARE
    v_result varchar2(32765);
    v_xml XMLType;
    BEGIN
    v_xml := XMLType('<PurchaseOrder xmlns="http://rapdrp.com/processcin/transactional/model/1.0/">
    <Reference>SBELL-2002100912333601PDT</Reference>
    <Actions>
    <Action>
    <User>SVOLLMAN</User>
    </Action>
    </Actions>
    <Reject/>
    <Requestor>Sarah J. Bell</Requestor>
    <User>SBELL</User>
    <CostCenter>S30</CostCenter>
    <ShippingInstructions>
    <name></name>
    <address>400 Oracle Parkway
    Redwood Shores
    CA
    94065
    USA</address>
    <telephone>650 506 7400</telephone>
    </ShippingInstructions>
    <SpecialInstructions>Air Mail</SpecialInstructions>
    <LineItems>
    <LineItem ItemNumber="1">
    <Description>A Night to Remember</Description>
    <Part Id="715515009058" UnitPrice="39.95" Quantity="2"/>
    </LineItem>
    <LineItem ItemNumber="2">
    <Description>The Unbearable Lightness Of Being</Description>
    <Part Id="37429140222" UnitPrice="29.95" Quantity="2"/>
    </LineItem>
    <LineItem ItemNumber="3">
    <Description>Sisters</Description>
    <Part Id="715515011020" UnitPrice="29.95" Quantity="4"/>
    </LineItem>
    </LineItems>
    </PurchaseOrder>');
    v_result := xmltype.extract(v_xml,'/PurchaseOrder/ShippingInstructions/name/text()','xmlns="http://rapdrp.com/processcin/transactional/model/1.0/"').getStringVal();
    dbms_output.put_line('v_result:'||v_result);
    END;
    In this the value in <name></name> tag is NULL.
    Please let me know if i can parse this XML.
    Regards,
    Himani

  • Parsing data with java is killing me

    i created some data in notepad
    which contains :: embedded in the data
    my loop gets to the :: and does not see the ::
    while
    (Strpos < (line.length() ) ) {
    index = Strpos +2;
    colons = (line.substring(Strpos, index)) ;
    System.out.println(colons);// i can see the value i'm looking at here
    if (colons != "::")
    displayline.append(line.substring(Strpos, Strpos + 1));
    Strpos++;
    the pgm always executes the displayline.append.
    is this because i created the data in notepad
    i'm really getting discouraged with java.

    Essentiallly what you're trying to do here is compare Strings. By using the == operator (or != in your case), what you are actually comparing is the address location, which is always going to return true for you, since the address are going to be different (not equal for your code example). Try changing your if statment to the following:String colonMatch = "::"
    if(!colons.equals(colonMatch)) // if you current search is not equal to a pair of colonsUsing the equals() method does a character by character comparison, which is what you are needing. I've made this mistake myself a few times, so no worries.
    James

  • Econometrics/Statistical computaion with Java - Need advice

    Dear All,
    I need to perform econometrics/statistical computaion for the bank. We were using Matlab from MathWorks.com. Recently, we are planning to perform computation with java instead of Matlab.
    e.g. below is the sample equation that I want to evaluate in java -
    &#8710;&#934;_^(-1) (SDP_t )_ =B_1 &#12310;&#8710;SDF&#12311;_(t-1 )+ B_2 &#12310;&#8710;XXX&#12311;_(t-2 ) + B_3 &#12310;&#8710;linear&#12311;_(t-1)+B_4 &#12310;&#8710;Linear&#12311;_(t-2)
    +Z_m
    My question is, I have not found API in java though which I can perform calculation. Also, we are performing this type of computation first time in java, does java supports all statistics calculation like standard deviation, mean distribution et cetera.
    I came across Apache commons-maths library which provides class related to maths/statistics. (http://commons.apache.org/math/api-1.2/index.html)
    Has anyone performed statistics/equation evaluation in java or with Apache commons-maths? Please share your thought?
    I appreciate your time reading my post.
    Edited by: rasmeh on Jan 28, 2010 12:06 PM
    Edited by: rasmeh on Jan 28, 2010 12:07 PM
    Edited by: rasmeh on Jan 28, 2010 12:11 PM

    the concept of mean distribution must be sth in econometrics that hasn't caught on.
    Java math does not define standard deviation or any other stat methods. it's quite easy to program though. to do linear algebra and optimization you will need to call C or Fortran libraries from java. no need to reinvent the wheel.
    cheers
    s.

  • Seeking advice for backing up Xserve G5 w/ RAID PCI card

    Hello all!
    I'm a newbie to Macs and server admin, and I have inherited the job of setting up a server at work for file storage. I'll do my best to give a concise description of our set-up - I'm looking for some advice on the last few odds and ends... mainly how we can backup the system.
    We bought an Xserve G5 with an option RAID PCI card. We have 3 500GB drives in the Xserve, configured to RAID 5 (giving us effectively 1TB of storage space). We will be using the server for data storage. About 20 computers will access the server over a network; we are using an assortment of Macs and PCS.
    I am seeking advice on backup systems for the server. In the event that the RAID5 fails, we don't want to lose our data. We just need a snapshot of the server; we don't need to archive data or to take the HD offsite. Our old server just used Retrospect to run incremental backups every night (with a complete clean backup once a month). Our current thought is to attach large external hard drive to our admin computer (not the server directly) and run nightly backups as before.
    The major points I have are:
    -Any thoughts on reliable 1 TB external drives?
    -Any recommendations on software that can backup from a RAID over a network? I found info for Retrospect Server 6.0 - it seems to do what we want, but is rather pricey.
    Thanks in advance for any advice! I really appreciate it!
    Xserve G5 Mac OS X (10.4.2)

    Greetings-
    We all started out as newbies at one time or another-no worries. That is why we are here.
    I personally use the Lacie branded drives. They are sturdy and reliable. My only thoughts here are to have at least three external drives-one for today's backup, one for a backup stored securely nearby, and one to be securely stored off-site. Rotate the drives daily so that your worst-case scenario will be a catastrophe that requires you to use a three-day old backup, depending upon how old your off-site backup is. Not ideal but better than the alternative. External drives are cheap enough these days to allow you to do this at a reasonable cost. Plus it is easy enough to throw one in a briefcase and tote it home for safety (just don't lose it!)
    I would stay away from Retrospect. If you search these forums you will find several instances of folks having some serious issues with the program. I use a program called Carbon Copy Cloner that does the job nicely for my basement server. There are ways to do the backups via the command line interface as well but I am not so familiar with those commands. You may have to dig a little deeper to find something that works for you.
    One of the other advantages of the FW external drive is that you can share it with other users, so perhaps you can set things up to have your network backups to go to that drive. Tis a thought.
    Luck-
    -DaddyPaycheck

  • XML with Java

    Hi,
    I am new in XML and I need to design a Java GUI interface for managing changes to xml data(inserting, deleting of nodes). But i have no idea on how the communication is going to be established (How to link java to xml..).
    Any help will be very very appreciated!
    Thank You
    cheers,
    jun

    if you use the latest JDK (1.4), you will have all what you need to manipulate XML in Java.
    then follow this tutorial: http://java.sun.com/webservices/docs/1.0/tutorial/doc/JAXPDOM.html
    it'll get you started!

  • How parse xml in java

    i wrote java client to invoke webservice(TIBCO) as a result i am getting back xml. now i have to parse xml and use the information. can anyone pls advise on this.
    thanks

    Cross-post
    http://forum.java.sun.com/thread.jspa?threadID=706827

Maybe you are looking for

  • I have to save as CMYK for print, but the colours are out of whack..

    hey all, I am designing something for a CD cover that is going to be printed at a print shop, They say they want their images in CMYK and prefer it in a PDF or highest quality JPEG.... So I have been working in CMYK, everything looks fine in photosho

  • PARSER UNEXPECTED_VALUE

    Hi All, My scenario is SOAP  to ABAP proxy, when I am testing the data thorugh SOAP UI tool, I am getting the error message as <?xml version="1.0" encoding="UTF-8"?> <SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">   <SOAP:Heade

  • One way child BPEL getting rolled back 11g

    Hi, I am stuck with a strange issue. Here is my design : Bpel1 1. Invoke : Call One way Bpel2 -> Bpel 2 calls DB adapter to insert data to Database 2. Throw rollback When i throw rollback in BPEL 1 both : BPEL 1 & BPEL 2 gets rolled back , I need BPE

  • Mountain Lion downloads but error on install

    I have downloaded Mtn Lion successfully but get this error when trying to install 'this copy of the install can't be verified. It may have been corrupted or tampered with during download. delete this copy and download a new one' I have done that and

  • How the ejb is bound to JNDI name

    I am very new to Oracle App server. In weblogic, we declare the jndi-name of an EJB in weblogic-ejb-jar.xml file. I did not see this in OC4J. Actualli I have written a simple stateful session bean and trying to access it through a standalone java cli