Parsing XML in a Custom Class Problem

Hi, I am trying to parse an XML file from a class within my web app. It isn't a servlet, just a custom class to parse the xml.
However, I keep getting a null document printed when I try to print the document to the log file. This is the class:public class XMLParser
     Document document;
     public XMLParser()
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          factory.setValidating(true);
          factory.setNamespaceAware(true);
          try
               DocumentBuilder builder = factory.newDocumentBuilder();
               document = builder.parse(new File("SiteDescriptor.xml"));
          catch(SAXException sxe)
               // Error generated during parsing
               Exception x = sxe;
               if(sxe.getException() != null)
                    x = sxe.getException();
               x.printStackTrace();
          catch(ParserConfigurationException pce)
               pce.printStackTrace();
          catch(IOException ioe)
               ioe.printStackTrace();
          System.out.println("\n\n\n\n\n\n\n"+document+"\n\n\n\n\n");
}I know this code works as I use the exactly the same code in another application with the same XML file.
This is the XML file:
<root host="http://localhost:8080">
     <branch name="Home Page" shortname="/" type="Home Page" instanceid="44987" typeid="1227">
          <branch name="Films Archive" shortname="/films" type="Branch" instanceid="96354" typeid="1778">
               <leaf name="Evil Dead" shortname="/films/evil_dead" type="Films" instanceid="58985" typeid="1147"/>
               <leaf name="1984" shortname="/films/1984" type="Films" instanceid="49741" typeid="1147" />
          </branch>
     </branch
</root>And this is what I get when i print the document to the log file:
[#document: null]
Does anyone know why I cant get the class to read the document? I'm not getting any file not found exceptions or any other errors in the log.
Cheers,
Paul

Hi duffymo, I have tried as you suggested. I created a ServletContextListener implementation and in my web.xml file I have defined the XML file as a <context-param> and I have also defined the listener.
The ServletContextListener implementation creates the XML file as a resource using getResourceAsStream() and passes the InputStream to my parser. However, the parser still doesn't seem to work and prints out a null document in the log file: [#document: null]. Any ideas??
The web.xml file:
           <context-param>
          <param-name>siteDescriptor</param-name>     
          <param-value>/WEB-INF/SiteDescriptor.xml</param-value>
     </context-param>
          <listener>
          <listener-class>cms.beans.InitializeXML</listener-class>
     </listener>
......and the ServletContextListener is:
public class InitializeXML implements ServletContextListener
     static InputStream in = null;
     public void contextInitialized(ServletContextEvent sce)
          ServletContext context = sce.getServletContext();
          String siteDescriptor = context.getInitParameter("siteDescriptor");
          try
               in = context.getResourceAsStream(siteDescriptor);
          catch(Exception e)
               context.log("Error creating xml resource: " + e);
     public void contextDestroyed(ServletContextEvent sce)
     public static InputStream getXMLResource()
          return in;
}Thanks,
Paul

Similar Messages

  • Loading XML using a custom class and accessing it from other classes?

    I began with a class for a movie clip rollover function
    FigureRollOver. It works marvellously. Three things happen:
    1) it loads XML from a file "mod1_fig1.xml" and uses another
    class, XMLMember, to retool the scoping of the XML so that I can
    get at it
    2) an onload call inside of XMLMember calls the myOnLoad
    function and transfers the XML into an array.
    3) so long as the array is finished building, rolling over a
    movie clip attaches a new movie clip with the rollover text in it.
    But I don't want all those functions in one because I need it
    to be more dynamic, starting with being able to load any old xml
    file instead of just "mod1_fig1.xml", plus it seems like
    overbuilding to have all of that in one class, so I've separated
    out the loading of the XML and building of the array into its own
    class, FigureXMLLoader. FigureRollOver is then left to just attach
    the rollover with text in it, extracted from the array built by the
    new class.
    Problem is, though the array builds inside FigureXMLLoader, I
    can't figure out how to make it available outside the class. I know
    that I'm constructing things in the wrong order, and that the array
    needs to be somehow built inside the class function to be
    available, but I can't figure out how to do that. A cruddy
    work-around is to put a function call at the end of the building of
    the array, which calls yet ANOTHER function on the main timeline of
    my .swf to put the array I've just built into a new variable. This
    works, but it's messy. It seems like I should be able to have one
    line of script in the .swf that generates an array on the main
    timeline (or just a public array) which I can then access from my
    FigureRollOver class:
    var myRollOvers:Array = new FigureXMLLoader("mod1_fig1.xml");
    Here is FigureXMLLoader (see comments in the code for more
    details) which obviously does not return an array as it is, because
    of all the working around I've had to do. Note the "testing"
    variable, which can be traced from the main timeline of the .swf,
    but I will get "not what I want" because of course the array hasn't
    been built yet, and never will be, inside of the declaration as it
    is. How do I get it in there so I can return an array?
    Thanks!

    Suggest you ask this question in the Actionscript forum as
    this forum is
    more tuned to database integration questions.
    You can create arrays outside a class and pass them into it
    by reference and
    visa versa build arrays inside a class and pass out via
    reference.
    The preferred approach is to place the array in a class and
    not expose it.
    Then add methods to use the array or should we say to use the
    class.
    Lon Hosford
    www.lonhosford.com
    Flash, Actionscript and Flash Media Server examples:
    http://flashexamples.hosfordusa.com
    May many happy bits flow your way!
    "maija_g" <[email protected]> wrote in
    message
    news:ed4i43$9v0$[email protected]..
    > Update: I've now put this on the main timeline of the
    .swf:
    >
    > myRollOversLoaded = false;
    > var myRollOvers:Array;
    > var roll_content = new FigureXMLLoader("mod1_fig1.xml");
    >
    > And inside the "myOnLoad" function in FigureXMLLoader,
    just after the
    > while
    > loop I've put this:
    >
    > _root.myRollOversLoaded = true;
    > _root.myRollOvers = figure_arr;
    >
    > The movie clip rollover won't act until
    myRollOversLoaded is true. It
    > works,
    > but it still seems klugey. Any suggestions for a more
    elegant solution
    > would be
    > appreciated.
    >

  • 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.

  • Creating custom class instances for XML nodes

    Hi guys,
    I'm trying to load an external XML document in my application
    and create an instance of a custom class for each node in the XML
    based on the value of some of their elements. The instances created
    will eventually end up in a DataGrid by the way. The problem I'm
    having is there seems to be many ways of doing small parts of this
    and I have no idea how to make them all gel. Initially I'm using
    HTTPService to load the XML file but I've seen people just use an
    XML object. Then, after that, I initially set the loaded XML to an
    ArrayCollection but others have used XMLList or XMLListCollection.
    I've no idea what's the best way to do this.
    Eventually, when I've created all of these instances by
    looping over the XML and creating them how will I make them
    bindable to the data grid? I'm guessing I'll have to group them
    somehow...
    Any help would be greatly appreciated. Thanks

    Hey Tracy,
    That is exactly what I was talking about in a previous post
    you replied to
    http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?catid=585&threadid=1344350
    Anyhow, Below is some code I created to do what your saying
    somewhat dynamically. The idea being you can have many different
    object types that you may want to populate with data from XML. In
    my case I am using e4x as the result type from my web services. At
    present I have about 6 different classes that call this function.
    I'd love to get some opinions on the function. Good bad or
    ???? Any improvements etc????
    package . . . .
    import flash.utils.describeType;
    import flash.utils.getDefinitionByName;
    import flash.utils.getQualifiedClassName;
    import mx.utils.ObjectUtil;
    * Utility class to convert xml based Objects to class
    instances.
    * Takes a value object as the destination and an xmlList of
    data
    * Look through all the items in the value object. Note we
    are using classInfo..accessor since
    * our objects are bound all variables become getter /
    setter's or accessors.
    * Also note, we can handle custom objects, arrays and
    arrayCollections.
    * History
    * 03.11.2008 - Steven Rieger : Created class
    public final class XMLToInstance
    public static function xmlToInstance( destinationObject :
    Object, sourceXMLList : XMLList ) : void
    // Get the class definition in XML, from the passed in
    object ( introspection so to speak )
    var classInfo : XML = describeType( destinationObject );
    // Loop through each variable defined in the class.
    for each ( var aVar : XML in classInfo..accessor )
    // If this is String, Number, etc. . . Just copy the data
    into the destination object.
    if( isSimple( aVar.@type ) )
    destinationObject[aVar.@name] = sourceXMLList[aVar.@name];
    else
    // Dynamically create a class of the appropriate type
    var className : String = aVar.@type;
    var ObjectClass : Class = getDefinitionByName( className )
    as Class;
    var newDestObject : Object = Object( new ObjectClass());
    // If this is a custom type
    if( isCustomType( className ) && ObjectClass != null
    // Recursively call itself passing in the custom data type
    and the data to store in it.
    // I haven't tested nested objects more than one level. I
    suppose it should work.
    // Note to self. Check.
    xmlToInstance( newDestObject, sourceXMLList[aVar.@name] );
    else
    // Must be some sort of Array, Array Collection . . .
    if( ObjectClass != null )
    var anXMLList : XMLList = new XMLList(
    sourceXMLList[aVar.@name] );
    for each( var anItem : XML in anXMLList )
    // I'm sure there are more types, just not using any of them
    yet.
    if( newDestObject is Array )
    newDestObject.push( anItem )
    else
    newDestObject.addItem( anItem );
    // Add the data to the destination object. . . .
    destinationObject[aVar.@name] = newDestObject;
    } // end function objectToInstance
    public static function isSimple( dataType : String ) :
    Boolean
    * This function is pretty self explanatory.
    * Check to see if this is a simple data type. Did I miss
    any?
    * History
    * 03.11.2008 - Steven Rieger : Created function
    switch( dataType.toLowerCase() )
    case "number":
    case "string":
    case "boolean":
    return true;
    return false;
    } // end isSimple
    public static function isCustomType( className : String ) :
    Boolean
    * This function is pretty self explanatory.
    * Check to see if this is a custom data type. Add them here
    as you need. . .
    * History
    * 03.11.2008 - Steven Rieger : Created function
    var aClassName : String = className.replace( "::", "."
    ).toLowerCase();
    aClassName = aClassName.substr( aClassName.lastIndexOf( "."
    ) + 1, aClassName.length - aClassName.lastIndexOf( "." ) );
    switch( aClassName )
    case "ndatetimevo":
    case "expenselineitemvo":
    return true;
    return false;
    } // end isCustomType
    } // end class
    } // end package

  • Problem Using Custom Classes in UCCX8.5.1 SU3

    Dear All,
    My team is facing problem in using Java custom classes for UCCX 8.5.1 SU3
    The problem is that we have created some conditional prompts for currency in different languages, our custom java class contains two mathods GetEnglishString(parameter set) and GetUrduString(parameter set). We are able to use/call both methods one by one and both at same time in CCX Editor and validate the script successfully but when we set the script as application it failed.
    We tried to use both methods one by one and found that script with GetEnglishString is working ok but when we place GetUrduString (alone as well) MIVR logs say that method is unknown altough CCX Editor does not give us any error. We triend to restard Administration and Engine Services several time but to no avail. If somebody know the reason and solution kindly share it ASAP.
    Regards
    Kashif Surhio

    Hi
    In that case I would double check you have uploaded the file, and restart the server completely. In testing we found that restarting the engine didn't always reload the classes.
    Aaron

  • Problem in parsing XML Schema

    I am trying to parse XML Schema using XSOM. The Schema has <xs:include>s
    e.g. I have first.xsd which includes second.xsd and second.xsd again includes third.xsd.
    First.xsd
    <xs:include schemaLocation="../Second.xsd">....
    Second.xsd
    <xs:include schemaLocation="Third.xsd">....
    When I parse "First.xsd" parser passes the correct path "C:/XSDSchema/Second.xsd"(First.xsd resides in "C:/XSDSchema/Schema/") to the EntityResolver's resolveEntity method. But for Second.xsd it passes "Third.xsd" only (Third.xsd resides in "C:/XSDSchema/" ) .
    Any Idea ?????

    Here is a screenshort of the part of my workflow:
    In the mappings of the "Set Value" activity, I have one line with those properties:
    Location: /process_data/bonusValidationForm/object/data/xdp/datasets/data/BonusValidationForm/buMan agerID
    Expression: /process_data/currentUser/object/@userId
    Where:
    bonusValidationForm is a process variable of my workflow that point my xdp form
    buManagerID is the textfield I want to set
    currentUser is a process variable (type User) that was well setted by the task Find BU Manager

  • Problem parsing xml in J2ME (using kxml2)

    Hello.
    May someone who knows how to use kxml help me please?
    I'll try to be straight forward. (Please excuse my imperfect English)
    My xml file look something like this:
    <?xml version="1.0" encoding="utf-8"?>
    <sample_tag1 xmlns:mysample="http://www.sample001.com/sample01schema">
    <feature name=”tag1_feature”>
         <test name=”xxxxx” id=”200” message=”Hello.”></test>
    </feature>
    <catalog name="shelf">
         <booklist name="book1" label="b1"></booklist>
         <booklist name="book2" label="b2"></booklist>
         <booklist name="book3" label="b3"></booklist>
    </catalog>
    </sample_tag1>
    And here's my code
              //http request
                   try{
                   //I can guarantee that the URL is valid
    httpConnection = (HttpConnection) Connector.open(URL);
    }catch(IOException ioe){
    ioe.printStackTrace();
                   //Create the parser
    KXmlParser parser = new KXmlParser();
    try{
                        //I use this code section to test if the xml file is properly placed in the inputStream.
    char[] tempChar = new char[500];
    isr = new InputStreamReader(httpConnection.openInputStream());
    isr.read(tempChar);
    for(int i=0; i<tempChar.length;i++){
    System.out.print(tempChar);
    //set the xml input
    parser.setInput(isr);
    //skip the "<?xml version="1.0" encoding="utf-8"?>" tag
    parser.nextTag();
    parser.require(XmlPullParser.START_TAG, null, "sample_tag1");
                        System.out.println("name : " + parser.getName());
    System.out.println("namespace : " + parser.getNamespace());
    parser.nextTag(); // ***1
    I compiled the app and run, here's the result:
    name : sample_tag1
    namespace :
    org.xmlpull.v1.XmlPullParserException: attr value delimiter missing! (position:START_TAG <feature name='http://www.sample001.com/sample01schema'>@3:15 in java.io.InputStreamReader@e938beb1)
    at org.kxml2.io.KXmlParser.exception(+47)
    at org.kxml2.io.KXmlParser.error(+45)
    at org.kxml2.io.KXmlParser.parseStartTag(+285)
    at org.kxml2.io.KXmlParser.nextImpl(+314)
    at org.kxml2.io.KXmlParser.next(+23)
    at org.kxml2.io.KXmlParser.nextTag(+24)
    at MyMidlet$ReadXML.run(MyMidlet.java:235)
    But when I comment the last line (parser.nextTag(); // ***1), here's the result:
    name : sample_tag1
    namespace :
    My code is the clone of the one in this tutorial:
    http://www.developer.com/ws/article.php/3759471
    where he get the weather forecast from Yahoo Weather RSS
    What did I do wrong? I tried looking up google for "attr value delimiter missing!" but found no useful information.
    Thank you in advance. =)

    Please read this topic. I posted an answer about parsing xml using kxml2
    http://forums.sun.com/thread.jspa?threadID=5291592&start=0&tstart=0
    Regards,
    David

  • Parsing XML problem

    I parse XML String -> Document the next way:
    public static Document parseXml(String fragment) {
    try {           
    DocumentBuilderFactory factory = DocumentBuilderFactory.
    newInstance();
    Document d = factory.newDocumentBuilder().parse(
    new InputSource(new StringReader(fragment)));
    return d;
    } catch (SAXException e) {
    } catch (ParserConfigurationException e) {
    } catch (IOException e) {
    return null;
    In desktop applications all works correctly, but when I invoke this function in servlet which is run under Tomcat, it returns empty Document data. Can anybody explain me, where to find solution ?

    How do you know it is returning "empty" Document data? And what do you mean by "empty"?

  • How do you store parsed XML data in an array

    Hi, i am trying to complete a small program which implements the SAX parser to parse an XML file. My problem is that i am writing a custom class to store the parsed data into an array, and then make the array available to the main program via a simple method which returns the array. I know this must be very simple to do, but i seem to have developed a mental block with this part of the program. I can parse the data and print all the elements to the screen, but i just cant figure out how to store all the data elements into the array. I will post the class which is supposed to do this, and ask anyone out there if they know what i'm doing wrong, and also, if there is a more effeicient way of achieving this ( i expect there definitely is!! but i have never used the SAX parser before and am getting confused by the API docs on it!!) Any help very much appreciated.
    Here is my attempt at coding the class to handle the parsed XML data
    class Sink extends org.xml.sax.helpers.DefaultHandler
         implements org.xml.sax.ContentHandler{
    Customer[] customers = new Customer[20];
         int count = 1;
         int x = 0;
         int tagCount = 0;
         String name;
    String custID;
         String username;
         String address;
         String phoneNum;
    public void startElement(String uri, String localName, String rawName, final org.xml.sax.Attributes attributes)throws org.xml.sax.SAXException{
    //count the number of <name> tags in the XML file
         if(rawName.equals("name")){
              tagCount++;
    public void characters(char[] ch, int start, int len){
    //get the current string
         String text = new String(ch, start, len);
         String text1 = text.trim();
    //there are 5 elements for each customer found in the XML file so when the count reaches 6
    // i reset this to 1
         if(count == 6){
         count = count - 5;
         if(text1.length()>0 && count == 1){
              name = text1;
              System.out.println(name);
              }else{
         if(text1.length()>0 && count == 2){
              custID = text1;
              System.out.println(custID);
                   }else{
                   if(text1.length()>0 && count == 3){
                   username = text1;
                   System.out.println(username);
                   }else{
                        if(text1.length()>0 && count == 4){
                        address = text1;
                        System.out.println(address);
                        }else{
                        if(text1.length()>0 && count == 5){
                             phoneNum = text1;
                             System.out.println(phoneNum);
                             //add data to the customer array
                             customers[x] = new Customer(name, custID, username, address, phoneNum);
    // increment the array index counter
                        x = x+1;
                        }//end of if
                        }//end else
                        }//end else
                   }//end else
              }//end else
    }//end of characters method
    public void endDocument(){
         System.out.println("There are " + tagCount +
         " <name> elements.");
    }//end of class Sink
    Before the end of this class i also need to make the array available to the calling program!!
    Any help would be much appreciated
    Thanks
    Iain

    Ok, yer going about this all the wrong way. You shouldn't have to maintain a count of all the elements. Basically you are locking yourself into the XML tags not only all being there but are assuming they are all in the same order. What you should do is in your characters() method, put all of the characters into a string buffer. Then, in endElement() (which you dont use btw, you should) you grab the information that is in the string buffer and store it into your Customer object depending on what the tagName is.
    Also, you should probably use a List to store all the Customer objects and not an single array, it's more dynamic and you arent locked into a set number of Customers.
    I wont do it all for you, but I'll give you a good outline to use.
    public class CustomerHandler extends DefaultHandler {
        private java.util.List customerList;  // List of Customer objects
        private java.util.StringBuffer buf;   // StringBuffer to store the string of characters between the start and end tags
        private Customer customer;  // Customer object that is initialized with each entry.
        public CustomerHandler() {
            customerList = new java.util.ArrayList();   // Initialize the List
            buf = new java.util.StringBuffer();   // Initialize the string buffer
        //  Make your customer list available to other classes
        public java.util.List getCustomerList() {
            return customerList;
        public void startElement(String nsURI, String sName, String tagName, Attributes attributes) throws SAXException {
            // Clear the String Buffer
            //  If the tagName is "Customer" then create a new Customer object
        public void characters(char[] ch, int start, int length) {
            //  append the characters into the string buffer
        public void endElement(String nsURI, String sName, String tagName) throws SAXException {
            // If the tagName is "Customer" add your customer object to the List
            // Place the data from the String Buffer into a String
            //  Depending on the tagName, call the appropriate set method on your customer object
    }

  • Ned help on JSP parsing XML

    Hi all.
    Im having problems on how to parse an xml by JSP
    Can anyone teach me how to parse an the XML below by jsp, without using taglibs. Im using JDOM...
    <Customer>
               <DetailsCustomer ID = 1>
               <Name>
                      John
               </Name>
               <DetailsCustomer ID = 2>
               <Name>
                     Michael
               </Name>
    <Customer>Thankz :)
    Hope for a kind reply :)

    Hi,
    Why would you like to parse the XML inside a JSP page? JSP are for rendering and not for parsing XML. The code to parse the XML should be put in an ordinary Java class instead.
    Parsing XML can be done in a number of ways...it all depends on what you want to do with the XML. Are you looking for XML -> Java Object then maybe you should look at XStream or JAXB.
    If you can tell me a little more about your use case maybe I can help you a little bit more.
    /klejs

  • Need help on parsing xml file...

    Hi all,
    I need to collect some data from an Xml file using java. I have the following code with me but I am unable to get the required result. I am unable to get the data from the tags belonging to the header and footer elements. Please find the code and the sample xml file below.
    Program to parse XML:
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class JobLogDetails3{
         //No generics
         List myJobs;
         Document dom;
         public JobLogDetails3(){
              //create a list to hold the job objects
              myJobs = new ArrayList();
         public void runJobDetails() {
              //parse the xml file and get the dom object
              parseXmlFile();
              //get each joblog element and create a job object
              parseDocument();
              //Iterate through the list and print the data
              printData();
         private void parseXmlFile(){
              //get the factory
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              try {
                   //Using factory get an instance of document builder
                   DocumentBuilder db = dbf.newDocumentBuilder();
                   //parse using builder to get DOM representation of the XML file
                   dom = db.parse("test.xml");
              }catch(ParserConfigurationException pce) {
                   pce.printStackTrace();
              }catch(SAXException se) {
                   se.printStackTrace();
              }catch(IOException ioe) {
                   ioe.printStackTrace();
         private void parseDocument(){
              //get the root elememt
              Element docEle = dom.getDocumentElement();
              //get a nodelist of <joblog> elements
              NodeList nl = dom.getElementsByTagName("*");
              if(nl != null && nl.getLength() > 0) {
                   for(int i = 0 ; i < nl.getLength();i++) {
                        //get the joblog element
                        Element el = (Element)nl.item(i);
                        //get the joblog object
                        Job J = getJob(el);
                        //add it to list
                        myJobs.add(J);
         * I take an joblog element and read the values in, create
         * an joblog object and return it
         * @param JobEl
         * @return
         private Job getJob(Element JobEl) {
              //for each <joblog> element get text or int values of
              //name ,id, age and name
              String jobServer = getTextValue(JobEl,"server");
              String jobName = getTextValue(JobEl,"name");
              String jobClient = getTextValue(JobEl,"machine_name");
              String jobStart = getTextValue(JobEl,"start_time");
              String jobType = getTextValue(JobEl,"type");
              String jobEnd = getTextValue(JobEl,"end_time");
              String jobSize = getTextValue(JobEl,"new_processed_bytes");
              //Create a new Job with the value read from the xml nodes
              Job J = new Job(jobServer,jobName,jobClient,jobStart,jobType,jobEnd,jobSize);
              return J;
         * I take a xml element and the tag name, look for the tag and get
         * the text content
         * i.e for <employee><name>John</name></employee> xml snippet if
         * the Element points to employee node and tagName is name I will return John
         * @param ele
         * @param tagName
         * @return
         private String getTextValue(Element ele, String tagName) {
              String textVal = null;
              NodeList nl = ele.getElementsByTagName(tagName);
              if(nl != null && nl.getLength() > 0) {
                   Element el = (Element)nl.item(0);
                   textVal = el.getFirstChild().getNodeValue();
              return textVal;
         * Calls getTextValue and returns a int value
         * @param ele
         * @param tagName
         * @return
         private int getIntValue(Element ele, String tagName) {
              //in production application you would catch the exception
              return Integer.parseInt(getTextValue(ele,tagName));
         * Iterate through the list and print the
         * content to console
         private void printData(){
              System.out.println("No of Jobs '" + myJobs.size() + "'.");
              Iterator it = myJobs.iterator();
              while(it.hasNext()) {
                   System.out.println(it.next().toString());
         public static void main(String[] args){
              //create an instance
              JobLogDetails JLD = new JobLogDetails();
              //call run example
              JLD.runJobDetails();
    Job Class
    public class Job {
         private String jobServer;
    private String jobName;
    private String jobClient;
    private String jobStart;
    private String jobType;
    private String jobEnd;
    private String jobSize;
         public Job(){
         public Job(String jobServer,String jobName,String jobClient,String jobStart,String jobType,String jobEnd,String jobSize ) {
              this.jobServer = jobServer;
              this.jobName = jobName;
              this.jobClient = jobClient;
    this.jobStart = jobStart;
              this.jobType = jobType;
    this.jobEnd = jobEnd;
    this.jobSize = jobSize;
         public String getjobServer() {
              return jobServer;
         public void setjobServer(String jobServer) {
              this.jobServer = jobServer;
         public String getjobName() {
              return jobName;
         public void setjobname(String jobName) {
              this.jobName = jobName;
         public String getjobClient() {
              return jobClient;
         public void setjobClient(String jobClient) {
              this.jobClient = jobClient;
    public String getjobStart() {
              return jobStart;
         public void setjobStart(String jobStart) {
              this.jobStart = jobStart;
    public String getjobType() {
              return jobType;
         public void setjobType(String jobType) {
              this.jobType = jobType;
    public String getjobEnd() {
              return jobEnd;
         public void setjobEnd(String jobEnd) {
              this.jobEnd = jobEnd;
    public String getjobSize() {
              return jobSize;
         public void setjobSize(String jobSize) {
              this.jobSize = jobSize;
         public String toString() {
              StringBuffer sb = new StringBuffer();
    sb.append(getjobServer());
              sb.append(",");
    sb.append(getjobName());
              sb.append(",");
              sb.append(getjobClient());
              sb.append(",");
              sb.append(getjobType());
              sb.append(",");
              sb.append(getjobStart());
              sb.append(",");
              sb.append(getjobEnd());
              sb.append(",");
              sb.append(getjobSize());
              sb.append(",");
              return sb.toString();
    Sample XML File:
    <?xml version="1.0" encoding="UTF-16" ?>
    - <joblog>
    <job_log_version version="2.0" />
    - <header>
    <filler>======================================================================</filler>
    <server>Job server: TGBBAK</server>
    <name>Job name: TGBSAP4-SQL-SQL DB Servers S2T - High-Weekly Full Backup</name>
    <start_time>Job started: 26 September 2011 at 01:00:04</start_time>
    <type>Job type: Backup</type>
    <log_name>Job Log: GFD_TGBBAK_71887.xml</log_name>
    <filler>======================================================================</filler>
    </header>
    <media_mount_date>Drive and media mount requested: 26/09/2011 01:00:04</media_mount_date>
    - <media_drive_and_media_info>
    <media_mount_date>Drive and media information from media mount: 26/09/2011 01:00:39</media_mount_date>
    <robotic_library_name>Robotic Library Name: HP 1</robotic_library_name>
    <drive_name>Drive Name: LTO4_2</drive_name>
    <slot>Slot: 43</slot>
    <media_label>Media Label: 000059L</media_label>
    <media_guid>Media GUID: {a6ca0062-7a6f-4b4b-8144-732ca25f2f9d}</media_guid>
    <media_overwrite_date>Overwrite Protected Until: 25/10/2011 19:24:58</media_overwrite_date>
    <media_append_date>Appendable Until: 02/10/2011 14:00:30</media_append_date>
    <media_set_target>Targeted Media Set Name: Weekly Tape</media_set_target>
    </media_drive_and_media_info>
    - <backup>
    <filler>======================================================================</filler>
    <title>Job Operation - Backup</title>
    <append_or_overwrite>Media operation - append.</append_or_overwrite>
    <compression>Compression Type: Hardware [if available, otherwise none]</compression>
    <verify_option>WARNING: The option 'Verify after backup completes' was not selected. Performing a verify operation to make sure that media can be read after the backup has completed is recommended.</verify_option>
    <filler>======================================================================</filler>
    - <machine>
    <machine_name>TGBSAP4.Tetley.Grp</machine_name>
    <info>Network control connection is established between 10.22.2.18:3271 <--> 10.22.2.4:10000</info>
    <info>Network data connection is established between 10.22.2.18:3301 <--> 10.22.2.4:3094</info>
    - <set>
    <set_resource_name>TGBSAP4.Tetley.Grp</set_resource_name>
    <tape_name>Family Name: "Media created 25/09/2011 13:59:55"</tape_name>
    - <volume>
    <display_volume>Backup of "TGBSAP4.Tetley.Grp "</display_volume>
    </volume>
    <description>Backup set #45 on storage media #1 Backup set description: "Weekly Full Backup"</description>
    <backup_type>Backup Method: Full - Back up entire database or filegroup</backup_type>
    <agent_started>Microsoft SQL Server Agent: Started</agent_started>
    <start_time>Backup started on 26/09/2011 at 01:01:45.</start_time>
    - <database>
    <database>Database PRD</database>
    </database>
    - <database>
    <database>Database master</database>
    </database>
    - <database>
    <database>Database model</database>
    </database>
    - <database>
    <database>Database msdb</database>
    </database>
    <end_time>Backup completed on 26/09/2011 at 02:42:25.</end_time>
    - <summary>
    <backed_up_database>Backed up 4 databases</backed_up_database>
    <new_processed_bytes>Processed 573363576542 bytes in 1 hour, 40 minutes, and 40 seconds.</new_processed_bytes>
    <vlm_hist_rateformat2>Throughput rate: 5432 MB/min</vlm_hist_rateformat2>
    </summary>
    <filler>----------------------------------------------------------------------</filler>
    </set>
    </machine>
    </backup>
    - <footer>
    <filler>======================================================================</filler>
    <end_time>Job ended: 26 September 2011 at 02:43:12</end_time>
    <engine_completion_status>Job completion status: Successful</engine_completion_status>
    <filler>======================================================================</filler>
    <completeStatus>19</completeStatus>
    </footer>
    </joblog>

    1. your code does not compile (in your main method you try to create an instance of a class which does not exist).
    2. your XML document is not well formed.
    +[Fatal Error] test.xml:34:74: The content of elements must consist of well-formed character data or markup.+
    org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.
    Maybe there are other problems but you can start by fixing these.

  • Parse XML in a java stored proc

    I am trying to parse an xml document in a java stored procedure. Just following my nose, I have developed a stored proc that works fine in development (outside the database using JRE 1.4.1) using the Xerces 2.5 parser. But, after having transferred the xerces xercesImpl.jar, xmlapis.jar, and my implementation class into oracle using loadjava when I call my stored proc the code throws an exception trying to build the document with an error like:
    NoClassDef exception org.apache.xerces.jaxp.DocumentFactoryBuilderImpl
    My Code looks like this:
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    InputStream is = getXMLAsInputStream(xml);
    try {
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse( is );
    ... parse the document ....
    catch (FactoryConfigurationError e) {
    // unable to get a document builder factory
    The exception caught is a FactoryConfigurtionError.
    I'm not particularly attached to xerces, I'm really just looking for a way to parse XML inside my java stored proc, so any help to solve my problem, or an alternative suggestion will be greatly appreciated.
    thanks
    Dale

    I looked again and sure enough the xerces implementation classes were missing. I had run a .cmd file containing these two lines, but it looks like only the first one ran...
    loadjava -u ncc/xyz@usd -v -r M:\Database\JavaGeocode\Xerces2_5_0\xml-apis.jar
    loadjava -u ncc/xyz@usd -v -r M:\Database\JavaGeocode\Xerces2_5_0\xercesImpl.jar
    Now I've got everything working fine with Xerces!
    Dale

  • 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

  • How to parse xml

    Hi All
    I want to parse xml document which contains more then one occurrence of particular element.
    I want to get some sub elements of that element and want take action on the basis of param tag inside this sub element.
    for example :
    <appender name="first" class="tempclass...">
    <param name="File" value="d:/test.log" />
    <filter class="">
    <param name="LevelToMatch" value="sdsds" />
    <param name="OtherParam" value="bla bla" />
    </filter>
    </appender>
    <appender name="second" class="tempclass...">
    </appender>
    my problem is how do i differentiate all "<appender>".
    I want values of "File" and "LevelToMatch" for each declaired appender
    and depending upon the values i want to take some decision.
    I dont know XML much
    I am using DOM parser.
    Please help me ASAP.
    Thanks in advance,

    hi,
    i hope u need to get the attribute values, right...
    if yes..create the DocumentBuilderFactory for the xml the uisng buildFactory method u will get the parser...from parser u cann go for anything....
    if u r not clearly, reply where do u struck...
    bye,
    suryakant.

  • How to parse XML against XSD,DTD, etc.. locally (no internet connection) ?

    i've searched on how to parse xml against xsd,dtd,etc.. without the needs of internet connection..
    but unfortunately, only the xsd file can be set locally and still there needs the internet connection for the other features, properties.
    XML: GML file input from gui
    XSD: input from gui
    javax.xml
    package demo;
    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.XMLConstants;
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    import org.xml.sax.SAXException;
    public class Sample1WithJavaxXML {
         public static void main(String[] args) {
              URL schemaFile = null;
              try {
                   //schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
                   File file0 = new File("AppSchema-C01-v1_0.xsd");
                   schemaFile = new URL(file0.toURI().toString());
              } catch (MalformedURLException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              //Source xmlFile = new StreamSource(new File("web.xml"));
              Source xmlFile = new StreamSource(new File("C01.xml"));
              SchemaFactory schemaFactory = SchemaFactory
                  .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
              //File file1 = new File("XMLSchema.dtd");
              //SchemaFactory schemaFactory = SchemaFactory
                   //.newInstance("javax.xml.validation.SchemaFactory:XMLSchema.dtd");
              Schema schema = null;
              try {
                   schema = schemaFactory.newSchema(schemaFile);
              } catch (SAXException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              Validator validator = schema.newValidator();
              try {
                validator.validate(xmlFile);
                System.out.println(xmlFile.getSystemId() + " is valid");
              } catch (SAXException e) {
                System.out.println(xmlFile.getSystemId() + " is NOT valid");
                System.out.println("Reason: " + e.getLocalizedMessage());
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }Xerces
    package demo;
    import java.io.File;
    import java.util.Date;
    import org.apache.xerces.parsers.DOMParser;
    public class SchemaTest {
         private String xmlFile = "";
         private String xsdFile = "";
         public SchemaTest(String xmlFile, String xsdFile) {
              this.xmlFile = xmlFile;
              this.xsdFile = xsdFile;
         public static void main (String args[]) {
              File file0 = new File("AppSchema-C01-v1_0.xsd");
              String xsd = file0.toURI().toString();
              SchemaTest testXml = new SchemaTest("C01.xml",xsd);
              testXml.process();
         public void process() {
              File docFile = new File(xmlFile);
              DOMParser parser = new DOMParser();
              try {
                   parser.setFeature("http://xml.org/sax/features/validation", true);
                   parser.setFeature("http://apache.org/xml/features/validation/schema", true);
                   parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                             xsdFile);
                   ErrorChecker errors = new ErrorChecker();
                   parser.setErrorHandler(errors);
                   System.out.println(new Date().toString() + " START");
                   parser.parse(docFile.toString());
              } catch (Exception e) {
                   System.out.print("Problem parsing the file.");
                   System.out.println("Error: " + e);
                   System.out.println(new Date().toString() + " ERROR");
                   return;
              System.out.println(new Date().toString() + " END");
    }

    Thanks a lot Sir DrClap..
    I tried to use and implement the org.w3c.dom.ls.LSResourceResolver Interface which is based on the SAX2 EntityResolver.
    please give comments the way I implement it. Here's the code:
    LSResourceResolver Implementation
    import org.w3c.dom.ls.LSInput;
    import org.w3c.dom.ls.LSResourceResolver;
    import abc.xml.XsdConstant.Path.DTD;
    import abc.xml.XsdConstant.Path.XSD;
    public class LSResourceResolverImpl implements LSResourceResolver {
         public LSResourceResolverImpl() {
          * {@inheritDoc}
         @Override
         public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
              ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
              LSInput input = new LSInputImpl(publicId, systemId, baseURI);
              if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                   input.setByteStream(classLoader.getResourceAsStream(XSD.XML));
              } else if (XsdConstant.PUBLIC_ID_XMLSCHEMA.equals(publicId)) {
                   input.setByteStream(classLoader.getResourceAsStream(DTD.XML_SCHEMA));
              } else if (XsdConstant.PUBLIC_ID_DATATYPES.equals(publicId)) {
                   input.setByteStream(classLoader.getResourceAsStream(DTD.DATATYPES));
              return input;
    }I also implement org.w3c.dom.ls.LSInput
    import java.io.InputStream;
    import java.io.Reader;
    import org.w3c.dom.ls.LSInput;
    public class LSInputImpl implements LSInput {
         private String publicId;
         private String systemId;
         private String baseURI;
         private InputStream byteStream;
         private String stringData;
         public LSInputImpl(String publicId, String systemId, String baseURI) {
              super();
              this.publicId = publicId;
              this.systemId = systemId;
              this.baseURI = baseURI;
         //getters & setters
    }Then, here's the usage/application:
    I create XMLChecker class (SchemaFactory implementation is Xerces)
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.XMLConstants;
    import javax.xml.stream.FactoryConfigurationError;
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import abc.xml.XsdConstant.Path.XSD;
    public class XMLChecker {
         private ErrorMessage errorMessage = new ErrorMessage();
         public boolean validate(String filePath){
              final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
              List<Source> schemas = new ArrayList<Source>();
              schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XML_SCHEMA)));
              schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XLINKS)));
              schemas.add(new StreamSource(classLoader.getResourceAsStream("abc/xml/AppSchema.xsd")));
              SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
              schemaFactory.setResourceResolver(new LSResourceResolverImpl());
              try {
                   Schema schema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
                   Validator validator = schema.newValidator();
                   validator.setErrorHandler(new ErrorHandler() {
                        @Override
                        public void error(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                   StreamSource source = new StreamSource(new File(filePath));
                   validator.validate(source);
              } catch (SAXParseException e) {
                   return false;
              } catch (SAXException e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              } catch (FactoryConfigurationError e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              } catch (IOException e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              return true;
         public ErrorMessage getErrorMessage() {
              return errorMessage;
    }Edited by: erossy on Aug 31, 2010 1:56 AM

Maybe you are looking for

  • Is there a plug-in like VocAlign that works in Logic Pro?

    I would like to use a plug-in that works like VocAlign. Is there anything around that works in Logic Pro .....what does everyone else use?

  • I am not able to change the color of my icloud calendar.

    Hi, my icloud calendar changed the color of my personal calender to purple and I have no chance to undo that. Everytime I try to change it back to blue it automatically jumps back to purple. Does anybody have an idea to solve this issue? Kind regards

  • [solved] xfce-wavelan-plugin

    Hi All, I have recently installed ArchLinux and have been experimenting ever since. I have my wifi set up through netcfg which uses multiple profiles so I can connect wherever I am. I have also settled with XFCE desktop environment, and am happy so f

  • Forum Find for 2009-April​-13

    Check out how BestBuy.com customers are rating our latest "Forum Find" for HD Media Player Solutions! Western Digital - WD TV HD Media Player for USB Storage Devices Model: WDAVN00BN | SKU: 8993217 Compatible with My Passport portable hard drives and

  • Dreamweaver CS3 under Mavericks

    I just upgraded my Mac OS from 10.6.8 (Snow Leopard) to 10.9.4 (Mavericks). My copy of Dreamweaver CS3 no longer works. The error message reads: "You can't open the application Dreamweaver because Power PC applications are no longer supported." The A