Xerces with SAX or DOM

I am using xerces (in jar form) to parse an XML file.
I've now read, after getting this to work, that xerces can use SAX or DOM.
How do I know which one I am using?

Actually, I have never used SAX for modifying attributes, but there is a lot of documentation available.
http://java.sun.com/webservices/docs/1.1/tutorial/doc/JAXPSAX.html#wp69937
I think this is a good example:
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.apache.xerces.parsers.SAXParser;
public class Trace extends DefaultHandler {
  int indent;
  void printIndent() {
    for (int i=0; i<indent; i++) System.out.print("-");
  public void startDocument() {
    System.out.println("start document");
  public void endDocument() {
    System.out.println("end document");
  public void startElement(String uri, String localName,
                           String qName, Attributes attributes) {
    printIndent();
    System.out.println("starting element: " + qName);
    indent++;
  public void endElement(String uri, String localName,
                         String qName) {
    indent--;
    printIndent();
    System.out.println("end element: " + qName);
  public void ignorableWhitespace(char[] ch, int start, int length) {
    printIndent();
    System.out.println("whitespace, length " + length);
  public void processingInstruction(String target, String data) {
    printIndent();
    System.out.println("processing instruction: " + target);
  public void characters(char[] ch, int start, int length){
    printIndent();
    System.out.println("character data, length " + length);
  public static void main(String[] args) {
    Trace t = new Trace();
    SAXParser p = new SAXParser();
    p.setContentHandler(t);
    try { p.parse(args[0]); }
    catch (Exception e) {e.printStackTrace();}
}

Similar Messages

  • Possible to overwrite parse method in DOM with SAX Handler?

    Hi,
    Is it possible to overwrite the parse method within DOM?
    What a want to do is:
         private Node parseXml( String text ) throws SAXParseException, SAXException, IOException, ParserConfigurationException
              SAXParserFactory factory = SAXParserFactory.newInstance();
                   factory.setNamespaceAware(true);
                   SAXParser parser = factory.newSAXParser();
                   TestHandler handler = new TestHandler();
                   // Parse the file
                   parser.parse(new InputSource(new StringReader(text)), handler);
              return (Node)handler.getRoot();
         } //end parseXml()The reason I want to use this is that within SAX I can write my own line counter so I keep a count of which node is on which line of text.
    What I was thinking is that I could use SAX to return DOM Nodes with the line number attached, possibly using the node.setUserData() method?!
    I have tried to play around with it and it doen't seem to work, can anyone help?
    Cheers Alex

    I have managaed to re-write my SAX parser to create a JTree, this works perfectly I can move through the tree and each line of text that corresponds to the node is highlighted.
    My problem is however that in my application I have used the DOM structure throughout so some of the functionality is lost.
    Is I understand that JAXP uses both SAX and DOM together, so I was wondering if it is possible to combine my sax parse method within the DOM?
    If anything is unclear please say and I will try and explain better. The main reason for doing this is that I want to keep a reference to which line of text each node of the dom tree represents. I have not been able to implemnet one in DOM however using SAX I have managed.
    Many thanks,
    Alex

  • NullPointerException with SAX

    I have developed a CSV to XML parser using a JAXP with SAX Events to parse the CSV file into a DOM tree.
    Well inside the parse() method I have the following code":
    public void parse(InputSource input) throws IOException, SAXException
    BufferedReader br = null;
    if( input.getCharacterStream() != null )
    br = new BufferedReader( input.getCharacterStream() );
    else if( input.getByteStream() != null )
    br = new BufferedReader( new InputStreamReader( input.getByteStream() ) );
    else if( input.getSystemId() != null )
    URL url = new URL( input.getSystemId() );
    br = new BufferedReader( new InputStreamReader( url.openStream() ) );
    else
    throw new SAXException( "Objeto InputSource invalido" );
    ContentHandler ch = getContentHandler();
    ch.startDocument();
    ch.startElement( "", "", "file", new AttributesImpl() );
    this.parseInput( br );
    ch.endElement( "", "", "file" );
    ch.endDocument();
    Problem is that whenever the app gets to the ch.startDocument() statement it throws an java.lang.NullPointerExecption. I have no idea why this is happening, I have tested the very same code with Xalan 2 and Xercer 2 parsers and it works without problems. But using the oracle xml parser v2 throws the Exception.
    Is this a bug? should I set tome of the Transformer's attributes to an specifica value to avoid this? Where could I find more info on processing SAX events?
    Thanks,
    Fedro

    Fedro,
    Did you try it using XDK v10?

  • How can I use a 3rd party XML parser such as xerces with OC4J ?

    Hi all tech experts,
    I am using Oracle Application Server 10g Release 2 (10.1.2) and i have
    installed Portal and Wireless and OracleAS Infrastructure on the same
    computer.
    i tried all the solutions on this thread
    Use of Xerces Parser in out application with Oracle App Server 9.0.4
    but still fighting.
    I have also posted this query on OTN on following thread
    How can I use a 3rd party XML parser such as xerces with OC4J?
    but no reply....
    Please help me on this issue.
    Since OC4J is preconfigured to use the Oracle XML parser which is xmlparserv2.jar.
    i have read the following article which states that
    OC4J is preconfigured to use the Oracle XML parser. The Oracle XML parser is fully JAXP 1.1 compatible and will serve the needs of applications which require JAXP functionality. This approach does not require the download, installation, and configuration of additional XML parsers.
    The Oracle XML parser (xmlparserv2.jar) is configured to load as a system level library of OC4J through it's inclusion as an entry in the Class-Path entry of the oc4j.jar Manifest.mf file. This results in the Oracle XML parser being used for all common deployment and packaging situations. You are not permitted to modify the Manifest.mf file of oc4j.jar.
    It must be noted that configuring OC4J to run with any additional XML parser or JDBC library is not a supported configuration. We do know customers who have managed to successfully replace the system level XML parser and the Oracle JDBC drivers that ship with the product, but we do not support this type of configuration due to the possibility of unexpected system behavior and system errors that might occur from replacing the tested and certified libraries.
    If you absolutely must use an additional XML parser such as xerces, then you have to start OC4J such that the xerces.jar file is loaded at a level above the OC4J system classpath. This can be accomplished using the -Xbootclasspath flag of the JRE.
    i have also run the following command
    java -Xbootclasspath/a:d:\xerces\xerces.jar -jar oc4j.jar
    but no success.
    How could i utilize my jar's like xerces.jar and xalan.jar for parsing instead of OC4J in-built parser ?
    All reply will be highly appreciated.
    Thnx in advance to all.
    Neeraj Sidhaye
    try_catch_finally @ Y !

    Hi Neeraj Sidhaye,
    I am trying to deploy a sample xform application to the Oracle Application Server (10.1.3). However, I encountered the class loader issue that is similar to your stuation. I tried all the three solutions but the application is still use the Oracle xml paser class. I am wondering if you have any insight about this?
    Thanks for your help.
    Xingsheng Qian
    iPass Inc.
    Here is the error message I got.
    Message:
    java.lang.ClassCastException: oracle.xml.parser.v2.XMLElement
    Stack Trace:
    org.chiba.xml.xforms.exception.XFormsException: java.lang.ClassCastException: oracle.xml.parser.v2.XMLElement
         at org.chiba.xml.xforms.Container.dispatch(Unknown Source)
         at org.chiba.xml.xforms.Container.dispatch(Unknown Source)
         at org.chiba.xml.xforms.Container.initModels(Unknown Source)
         at org.chiba.xml.xforms.Container.init(Unknown Source)
         at org.chiba.xml.xforms.ChibaBean.init(Unknown Source)
         at org.chiba.adapter.servlet.ServletAdapter.init(ServletAdapter.java:153)
         at org.chiba.adapter.servlet.ChibaServlet.doGet(ChibaServlet.java:303)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
         at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:870)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:451)
         at com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:299)
         at com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:187)
         at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:595)
    Caused by: java.lang.ClassCastException: oracle.xml.parser.v2.XMLElement
         at org.chiba.xml.xforms.Instance.iterateModelItems(Unknown Source)
         at org.chiba.xml.xforms.Bind.initializeModelItems(Unknown Source)
         at org.chiba.xml.xforms.Bind.init(Unknown Source)
         at org.chiba.xml.xforms.Initializer.initializeBindElements(Unknown Source)
         at org.chiba.xml.xforms.Model.modelConstruct(Unknown Source)
         at org.chiba.xml.xforms.Model.performDefault(Unknown Source)
         at org.chiba.xml.xforms.XFormsDocument.performDefault(Unknown Source)
         at org.chiba.xml.xforms.XFormsDocument.dispatchEvent(Unknown Source)
         at org.apache.xerces.dom.NodeImpl.dispatchEvent(Unknown Source)
         ... 18 more

  • Is there any possibility to combine XPath with SAX in Java?

    HI Gentlemen,
    I have an XML instance to parse. One solution works with XPath and Document builder. However, the tree in memory is too big so that I can not build it in my storage (8 GB). Does anyone of you know a method where I use an XPath expression (Java) to select a node but with a better parser (e g SAX) which is not so space hungry? Direct access of nodes is obligatory.
    Thanks, kind regards from
    Miklos HERBOLY

    As SAX  parsers do not build a DOM structure and XPath requires a DOM structure to select elements from, XPath is not usable with SAX, but some analysers support setting the XPath expressions to analyse before invoking the SAX parser and provide the result for XPath expressions.
    Refer
    https://code.google.com/p/xpath4sax/

  • XML - SAX or DOM?

    Hi folks,
    I'm on the verge of emotional breakdown trying to get my head around working with XML in Java, and I would really appreciate a bit of help.
    What I would like to do is to store database metadata in an XML file.
    The steps I have taken so far are to read the metadata into a structure of objects (a metadata object that containts arraylists of tables objects that contain arraylists of columns object. Each of these object types holds information about the table or column concerned (table name, column type etc).
    I'm stuck when it comes to deciding whether to use SAX or DOM to write / read these files.
    Now, I understand that SAX is for sequential access, and DOM is for situations where you'd like to manipulate the XML tree. I guess that, given the nature of my data structure DOM would make more sense? Then I can define a node for each table, then off them, define a node for each column... Or am I missing the point here?
    Can anyone give me a nudge in the right direction?
    Thanks in advance
    s.

    Thanks for replying!
    Duffymo, I'd rather keep the xml content to the data
    to make the files easy to edit / write by hand.Not following you here.
    I understand that you want XML files, but XStream can take them and turn them into Java objects for you. Conversely, you can take a graph of Java objects and serialize them as XML.
    No worries about DOM or SAX that way.
    %

  • Changing xmlschema while parsing with sax

    Hello world,
    I`m using the sax-parser (xerces) and i want to combine different schema-files to parse an xml-String;
    <root>
         <intervall>1,5</intervall>
         <nix>jetzt echt nix!</nix>
         <testtag>
              <text>huhu joe</text>
         </testtag>
         <theLast>das letzte element</theLast>
    </root>e.g. i want to parse the tag testtag with another schema ??
    does anyone have an idea or a sample coding ??
    thank you very much

    thank you for the reply, but i want to change the Schema file while parsing the xmlString with Sax, without manipulation the xmlString;
    the xml-String i get is fixed;
    wish you all a great sunday

  • In Java Mapping Whether to SAX or DOM ?

    While implementing Java Mapping which of the following SAX , DOM parsers  is the most efficient way to implement it.
    I mean considering the voulume of data in the XML format is large which  usage will give me most  optimal performance .
    It would be nice if someone could give a sample most  optimal java code using JAXP where  input stream is read  and after  processing written to  output stream.
    regards
    Nilesh Taunk.

    Hi Nilesh,
    >>>While implementing Java Mapping which of the following SAX , DOM parsers is the most efficient way to implement it.
    there's no one good answer fot this question
    except: it depends:)
    SAX and DOM are a little different parsers
    so it depends what will your java mapping
    have to do: if it will change the
    structure or maybe it will only change a few tags,
    or maybe it will do something else
    have a look at the page below to read a simple
    comparision between SAX and DOM
    http://www.scit.wlv.ac.uk/~jphb/cp2101/week4/XML_Parsing.html
    or this thread:
    http://www.biglist.com/lists/xsl-list/archives/200301/msg01318.html
    they will give you some idea which one to choose
    depending on your requirements
    BTW
    remember use java mappings only
    if you cannot use graphical mapping (very easy debugging)
    and if your document cannot be parsed (maybe huge documents)
    with XSLT which is supported by many graphilal tools
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions">XI FAQ - Frequently Asked Questions</a>

  • Edit an XML file with SAX

    Dear all, I am so confused�.
    I have been trying for the last few days to understand how sax works� The only thing I understood is:
    DefaultHandler handler = new Echo01();
    SAXParserFactory factory = SAXParserFactory.newInstance();
            try {
                out = new OutputStreamWriter(System.out, "UTF8");
                SAXParser saxParser = factory.newSAXParser();
                saxParser.parse(file , handler);
            } catch (Throwable t) {
                t.printStackTrace();
            System.exit(0);
        }Ok, I assign the SAXParser the xml file and a handler. The parser parses and throws events that the handler catches. By implementing some handler interface or overriding the methods of an existing handler (e.g DeafultHandler class) I get to do stuff�
    But still, suppose I have implement startElement() method of DefaultHandler class and I know that the pointer is currently placed on an element e.g. <name>bob</name>. How do I get the value of the element, and if I manage to do that, how can I replace�bob� with �tom�?
    I would really appreciate any help given� just don�t recommend http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/ because although there are interesting staff in there, it does not solve my problem�

    Maybe SAX is not the right tool for you.
    With SAX, you implement methods like startElement and characters that get called as XML data is encountered by the parser. If you want to catch it or not, the SAX parser does not care. In your case, the "bob" part will be passed in one or more calls to characters. To safely process the data, you need to do something like build a StringBuffer or StringBuilder in the constructor of the class, and then in the startElement, if the name is one you want to read, set the length to zero. In the characters method, append the data to the StringBuilder or StringBuffer. In the endElement, do a toString to keep the data wherever you want.
    This works for simple XML, but may need to be enhanced if you have nested elements with string values that contain other elements.
    On the other hand, if your file is not huge, you could use DOM. With DOM, (or with JDOM, and I would expect with Dom4J -- but I have only used the first two) you do a parse and get a Document object with the entire tree. That allows you to easily (at least it is easy once you figure out how to do it) find a node like the "name" element and change the Text object that is its child from a value of "bob" to "tom". With DOM, you can then serialize the modified Document tree and save it as an XML file. SAX does not have any way to save your data. That burden falls to you entirely.
    Dave Patterson

  • Performance sax vs dom

    Hi All,
    I have build a xml interface for a java application.
    I parse the xml files using dom parser, get the data
    and pass it to the java application. I know that DOM
    builds a in memory tree of the xml file.
    Will this degrade the performance of my application.
    Will it be better to use a SAX parser instead?
    Regards
    Milind

    It really depends on the size of the data that you are parsing. Parsing big XML files with DOM means you have a big tree in memory using up lots of memory and CPU. With SAX it will just take more time to process the XML than it would a smaller file.
    The only way to know for sure if it makes a difference for you is to try both approaches using live data. It doesn't help to profile them if you are using a test XML file that is half the size of what you are planning on using in production.
    So, the answer to your question is "It depends".

  • Does jdk1.4 come with an inbuilt DOM parser?

    Hello,
    I would just like to know if jdk1.4 comes with an inbuilt DOM parser? i.e. are there any API's, for parsing an xml document, inbuilt within jdk1.4??If yes, can anyone tell me how am i supposed to parse an input xml file and what are the API's present??? thnx in advance

    This works with JDK 1.4:
    import org.w3c.dom.Document;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory ;
    import org.xml.sax.InputSource;
    import java.io.InputStream;
    public class a {
        public Document doit(InputStream is)
        throws java.io.IOException,org.xml.sax.SAXException,javax.xml.parsers.ParserConfigurationException
            javax.xml.parsers.DocumentBuilderFactory dbf=javax.xml.parsers.DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource isrc = new InputSource( is );
            Document document = db.parse(isrc);
            return document;
    }

  • How to add attribute to Element with SAX

    Hi,
    I'm parsing XML document with SAX using DefaultHandler.
    How can I add attribute to start tag?

    Is this right????????????Yes, it's right. Everything everybody except you has said in this thread has been right.

  • Processing unfinished stream with SAX

    Hi,
    I'm just writing some kind of a jabber plugin in java. I've decided to use sax for parsing server responses. However I've encountered a problem with sax.
    saxParser.parse(inputStream, this);Problem is, that events (such as startElement) are called after the connection (streams read method returns with -1) is closed. Is there any way to force sax to raise event as soon as the tag is read?
    Any help will be greatly appreciated.
    Regards
    Versor
    Edited by: versor on Nov 2, 2007 3:20 AM

    versor wrote:
    ... Problem is, that events (such as startElement) are called after the connection (streams read method returns with -1) is closed. Is there any way to force sax to raise event as soon as the tag is read? ...Fully circumvent the problem parsing the buffered stream.

  • Can I parse non-wellformed XML with SAX at all?

    Hi all,
    i was wondering whether its possible at all to parse XML that is not well formed with SAX.
    e.g. A HTML file that doesnt close tags and stuff like that.
    I tried implementing the fatal() method of the Handler in a a way that it consumes the exception but does not rethrow it.
    Also I tried setting the validation property to false. Both with no success.
    Any help would be appriciated.
    thx
    philipp

    Your experiments tell you the answer.
    If you have HTML tag soup, why not just run it through JTidy or HTMLTidy to make it into well-formed XHTML?

  • Using Xerces with Java Web Start

    I read that there might be problems using xerces with Java Web Start, because JWS uses Sun's implementation of JAXP internally. My application needs Xerces and I think I am able to get it working using the following settings in the JNLP file:
    <resources>
    <j2se version="1.3"/>
    <jar href="xerces-1.4.3.jar"/>
    <property name="javax.xml.parsers.DocumentBuilderFactory" value="org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"/>
    </resources>

    Hi,
    I have packaged the xerces jar into my code jar and it does work. HTH
    Aniruddha

Maybe you are looking for

  • Reconciliation Accounts

    Hi, Please some one explain what is Reconciliation Account? what is the purpose of it in IR and IP. Please guid me with example. Thanks, Pria.

  • AE not working with Leopard and fed up

    It happened a while ago, and set it up again, and again, again. It all stated after upgrading to Leopard Today I was about to listen to some music through AE, and once again it didn't work. I had the green light on, it shows as connected in my router

  • Retrieve values, irrespective of case sensitive

    Hi all, How to retrieve values, irrespective of case sensitive. For Examle, column_value = "name" when i try to retrive by using select *  from table where column_value = 'NAME' But when i use the following query it is working select *  from table wh

  • Retail:Regarding the backend settings for Artilce master data

    Hi SAP Gurus,                         Can anyone tell me  the IMG settings that we do for Article master in Retail.I am expecting the step by step procedure for doing the  IMG settings.explain me in details in forum or you can mail to my personal mai

  • Why do i get a busy signal when calling my pre paid flip phone?

    I recently activated a old pre paid flip phone and I added minutes with a refill card on my verizon wireless account online.  It shows the payment as well as the calls I made to it  but it never lets me get through to the person.  What is the glitch?