StAX or SAX??

Hi everybody,
I�ve got an SOAP-Message stored in a byte-array data:
// copy the data (SOAP) from udp packet
byte[] data = new byte[packet.getLength()];
System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength());Now I like to have the SOAP-Envelope of the SOAP-Message. Does it make more sense to use StAX or SAX for this job??? How would the solution (with the byte-array) be realized??
Thanks for your help,
Chris

Ok, it works fine with StAX and xmlbeans:
byte[] data = new byte[packet.getData().length];
data = packet.getData();
try {
    XmlObject xobj = Factory.parse(new String(data));
    XMLStreamReader xmlreader = XMLInputFactory.newInstance()
                         .createXMLStreamReader(xobj.newReader());
    StAXBuilder builder = new StAXSOAPModelBuilder(xmlreader);
    SOAPEnvelope envelope = (SOAPEnvelope)   
                                         builder.getDocumentElement();
} catch (Exception e) {
    e.printStackTrace();
}Greetz,
Chris

Similar Messages

  • Extract data from xml file and insert into another exiting xml fil

    hello,
    i am searching extract data from xml file and insert into another exiting xml file by a java program. I understood it is easy to extract data from a xml file, and how ever without creating another xml file. We want to insert the extracted data into another exiting xml file. Suggestions?
    Regards,
    Zhuozhi

    If the files are small, you can load the target file in a DOM document, insert the data from the source file and persist the DOM.
    If the files are large, you probably want to use a StAX or SAX.

  • SAX succeeds, but StAX fails

    Hy!
    I tried to parse PubMed (a biomedical article database) with SAX and
    also StAX. The last one failed, but I am not sure why (see Exception
    below).
    Why does SAX succeed and StAX don't? The XML document seems to be fine (see
    http://www.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&id=11748933
    Any suggestions?
    Kai
    StAX example:
    String address = "http://www.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&id=11748933";
    URL url = new URL(address);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(url.openConnection().getInputStream());
    while(parser.hasNext()) {
           switch(parser.getEventType()) {
            parser.next();
    }Error message:
    javax.xml.stream.XMLStreamException: ParseError at [row,col]:[50,39]
    Message: A '(' character or an element type is required in the
    declaration of element type "PubMedPubDate".
    SAX example:
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    SAXParser parser = parserFactory.newSAXParser();
    parser.parse(url.openConnection().getInputStream(), new
    PubmedEFetchHandler());(PubmedEFetchHander is a simple DefaultHandler with some debugging
    output).
    Edited by: feldus on Mar 6, 2008 11:38 AM

    Have you looked at the usual suspects, such as disk space, file permissions etc.?
    Generally, if/when one of the tools fails, I run it from the command line. To figure out the command line, take a look in the log file and you'll see the command that it ran. By running it from the command line, you usually get a better idea of why it failed.
    Bob

  • Stax & sax writing character encoding?

    hello,
    i need to rip html tags & put them in xml files ...
    before i write with
    writer.writeStartElement(docXmlTagNames12);
    writer.writeCharacters(deTags[i]);
    System.out.println("writing tag:"+deTags[i]);
    writer.writeEndElement();
    writing tag gives: writing tag:Leden van het Comit��
    and in the xml file the "��" is scrambled:
    <notificatieAan>Leden van het Comit��notificatieAan>
    here it shows as a jaanses sign but with me it shows as a small rectangle ...
    anybody knows how i should deal with this problem???
    thanks

    this is the whole code:
    try{
    XMLOutputFactory factory=XMLOutputFactory.newInstance();
    XMLStreamWriter writer=factory.createXMLStreamWriter(
    new java.io.FileWriter(xmlFile.toString()));
    writer.writeStartDocument();
    writer.writeStartElement(rootTag1);
    for (int i=1;i<docXmlTagNames12.length;i++){
         writer.writeStartElement(docXmlTagNames12);
         writer.writeCharacters(deTags[i]);
         System.out.println("writing tag:"+deTags[i]);
         writer.writeEndElement();               
    writer.writeEndElement();          
    writer.writeEndDocument();
    writer.close();
    catch (XMLStreamException e){
    e.printStackTrace();
    catch (IOException e){
    e.printStackTrace();

  • "Right" way to mix SAX and DOM in app

    I'm writing a standalone desktop application that reads and stores data as XML files. Eventually, it might be converted to use some web services, but it's not a priority right now.
    What I need to do is to use an XML file, which could be large, as kind of a database -- there are many entries, each with a unique identifier, and the application will query the file to find those it needs to match and returns those as objects I'm mapping.
    At the moment, because this is a personal project and I'm using it to learn more technologies, I'm trying to (somewhat artificially) restrict myself to the pure Sun APIs. So far, my investigations have pointed to JAXP (by including Java EE 5 libraries) with StAX (including JAX-WS). Which raises two questions:
    1) To do this "right", do I really need to bundle my app with the entire JaveEE+Metro stack?
    2) Is there a better solution than StAX that's fully Java 5 compliant, even if it means stepping out of the Sun box? I haven't found many references to other solutions that are more recent than 2004. Is parsing XML on an app that has nothing to do with an appserver that uncommon?

    More likely than not, I won't be abstracting to that degree. If the current structure isn't right, I'd update the app instead of storing that kind of information in more files.
    I imagine at this point an example would be more effective. The app is itself more of an inventory browser that can jump around different searches dynamically. As an illustration, imagine that it's an inventory for DVDs. One central file will be your collection (with each entry containing a movie ID, date of purchase, etc). Another file would be more static, a list of DVDs themselves. These entries would contain information about the package itself -- how many discs? What's the title of the package? Which special features does it have? It would also point to an entry in yet another file which would have information about the film, containing biographies of the people listed under the movie credits.
    Basically, I want a flatfile database that I can do joins on that are split up into different files. There are few files (here, one) that will be constantly updated by the user. The others could be modified if needed, but it's not going to be optimized for it. (For example, you could own a DVD that nobody's ever heard of, and put in the info yourself.) Periodically, one or more of the more static files is updated and will be downloaded into the app.
    One of the advantages I see for this is that, in the future, I could with few changes turn this into more of a web service. Instead of pushing changes in those few files, the app would look to a web service for the data it would now find in files on the user's hard drive. But for now, it also has to be one standalone package.
    To answer the question, the file that will most commonly be updated by the user is the one that I don't have problems loading into memory in full. It's the other data that it links to which I want to be able to search and load into objects dynamically. My current implementation is to run the file through SAX and grab the data as it sees it, but it's really ugly. That could very well be how I'm using it and not because I'm trying to shoehorn some functionality into a technique it doesn't fit, but I'd like to find that out. ;)

  • Stax reading /writing need help from xml guru plz

    hi, i have been told that stax reading /writing should involve no overhead and that is why i use it and i am now able to write my large data to file, but using my reader i seem to run out of memory, using netbeans profiler i ahve found that char[] seems to be the problem,
    by backtracing i ahve found that javax.xml.parser.SAXParser.parse calls the xerces packages which eventually leads to the char[ ], now my code for my reader is attatched here...
    package utilities;
    import Categorise.Collection;
    import Categorise.Comparison;
    import Categorise.TestCollection;
    import java.io.IOException;
    import javax.xml.parsers.*;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.Attributes;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import measures.Protocol;
    * @author dthomas
    public class XMLParser extends DefaultHandler
        static Collection collection = new Collection();
        List<Short> cList;
        List<Comparison> comparisonList;
        File trainFileName;
        File testFileName;
        TestCollection tc;
        List<TestCollection> testCollectionList;
        List<File> testFileNameList = new ArrayList<File>();
        List<File> trainFileNameList = new ArrayList<File>();
        boolean allTrainsAdded = false;
        Protocol protocol;
        List<File> trainingDirList;
        File testingDir;
        int counter = 0;
        File[ ] trainingDirs;
        File[ ] trainingFileNames;
        File[ ] testFileNames;
        TestCollection[ ] testCollections;
        Comparison[ ] comparisons;
        Comparison c;
        short[ ] cCounts;
        String order;
        String value;
        File trainDir;
        /** Creates a new instance of XMLParser */
        public XMLParser() {
        public static Collection read( File aFile )
            long startTime = System.currentTimeMillis();
            System.out.println( "Reading XML..." );
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp;
            try {
                sp = spf.newSAXParser();
                sp.parse( aFile, new XMLParser() );
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (SAXException ex) {
                ex.printStackTrace();
            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            long endTime = System.currentTimeMillis();
            long totalTime = ( endTime - startTime ) / 1000;
            System.out.println( "Done..."  + totalTime + " seconds" );
            return collection;
        public void startElement(String uri,String localName,String qName, Attributes attributes)
            if( qName.equals( "RE" ) )
                testCollectionList = new ArrayList<TestCollection>();
            else if( qName.equals( "p") )
                boolean isConcatenated = new Boolean( attributes.getValue( "c" ) );
                boolean isStatic = new Boolean( attributes.getValue( "s" ) );
                protocol = new Protocol( isConcatenated, isStatic );
            else if( qName.equals( "trdl" ) )
                trainingDirList = new ArrayList<File>();
            else if( qName.equals( "trd" ) )
                trainDir = new File( attributes.getValue( "fn" ) );
                trainingDirList.add( trainDir );
            else if( qName.equals( "td" ) )
                testingDir = new File( attributes.getValue( "fn" ) );
            else if( qName.equals( "TC" ) )
                counter++;
                System.out.println( counter );
                comparisonList = new ArrayList<Comparison>();
                testFileName = new File( attributes.getValue( "tfn" ) );
                testFileNameList.add( testFileName );
                tc = new TestCollection( );
                tc.setTestFileName( testFileName );
            else if ( qName.equals( "r" ) )
             order = attributes.getValue( "o" );
                value = attributes.getValue( "v" );
                cList.add( Short.parseShort( order ), new Short( value ) );
            else if( qName.equals( "c" ) )
                cList = new ArrayList<Short>();
                trainFileName = new File( attributes.getValue( "trfn" ) );
                if( !allTrainsAdded )
                    trainFileNameList.add( trainFileName );
        public void characters(char []ch,int start,int length)
            //String str=new String(ch,start,length);
            //System.out.print(str);
        public void endElement(String uri,String localName,String qName)
            if (qName.equals( "c") )
                allTrainsAdded = true;
                cCounts = new short[ cList.size() ];      
                for( int i = 0; i < cCounts.length; i++ )
                    cCounts[ i ] = cList.get( i );
                c = new Comparison( trainFileName, tc );
                c.setcCounts( cCounts );
                this.comparisonList.add( c );
            else if( qName.equals( "TC" ) )
                comparisons = new Comparison[ comparisonList.size() ];
                comparisonList.toArray( comparisons );           
                tc.setComparisons( comparisons );
                testCollectionList.add( tc );
            else if( qName.equals( "RE" ) )
                testCollections = new TestCollection[ testCollectionList.size() ];
                testCollectionList.toArray( testCollections );
                collection.setTestCollections( testCollections );
                testFileNames = new File[ testFileNameList.size() ];
                testFileNameList.toArray( testFileNames );
                collection.setTestingFiles( testFileNames );
                //String[ ] testCategories = new String[ testCategoryList.size() ];
                //testCategoryList.toArray( testCategories );
                //collection.setTestCategories( testCategories );
                trainingFileNames = new File[ trainFileNameList.size() ];
                trainFileNameList.toArray( trainingFileNames );
                collection.setTrainingFiles( trainingFileNames );
                //String[ ] trainingCategories = new String[ trainCategoryList.size() ];
                //trainCategoryList.toArray( trainingCategories );
                //collection.setTrainingCategories( trainingCategories );
                collection.setProtocol( protocol );
                trainingDirs = new File[ trainingDirList.size() ];
                trainingDirList.toArray( trainingDirs );           
                collection.setTrainingDirs( trainingDirs );
                collection.setTestingDir( testingDir );
         //else
             //System.out.println("End element:   {" + uri + "}" + localName);
    }i thought it may have been a recursive problme, hence having so many instance variables instead of local ones but that hasn't helped.
    all i need at the end of this is a Collection which holds an array of testCollections, which holds an array of cCounts and i was able to hold all of this in memory as all i am loading is what was in memory before it was written.
    can someone plz help
    ps when i use tail in unix to read the end of the xml file it doesnt work correctly as i cannot specify the number of lines to show, it shows all of the file as thought it is not split into lines or contains new line chars or anything, it is stored as one long stream, is this correct??
    here is a snippet of the xml file:
    <TC tfn="
    /homedir/dthomas/Desktop/4News2/output/split3/alt.atheism/53458"><c trfn="/homed
    ir/dthomas/Desktop/4News2/output/split0/alt.atheism/53586"><r o="0" v="0"></r><r
    o="1" v="724"></r><r o="2" v="640"></r><r o="3" v="413"></r><r o="4" v="245"></
    r><r o="5" v="148"></r><r o="6" v="82"></r><r o="7" v="52"></r><r o="8" v="40"><
    /r><r o="9" v="30"></r><r o="10" v="22"></r><r o="11" v="16"></r><r o="12" v="11
    "></r><r o="13" v="8"></r><r o="14" v="5"></r><r o="15" v="2"></r></c><c trfn="/
    homedir/dthomas/Desktop/4News2/output/split0/alt.atheism/53495"><r o="0" v="0"><
    /r><r o="1" v="720"></r><r o="2" v="589"></r><r o="3" v="349"></r><r o="
    please if anyone has any ideas from this code why a char[] would use 50% of the memory taken, and that the average age seems to show that the same one continues to grow..
    thanks in advance
    danny =)

    hi, i am still having lo luck with reading the xml data back into memory, as i have said before, the netbeans profiler is telling me it is a char[] that is using 50% of the memory but i cannot see how a char[] is created, my code doesn't so it must be the xml code...plz help

  • XML validation with StAX

    Hi,
    I have a requirement to validate XMLs during JAXB unmarshalling and during StAX parsing. The schema is packaged in a jar. I am able to successfully read the schema, and validate the XML during unmarshalling by setting the schema in the unmarshaller (through setSchema()).
    However, I am not able to validate it with StAX using the same schema and same XML.
    Here is the code snippet for StAX:
    StringReader stringReader = new StringReader(inputXMLStr);
    XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(stringReader);
    EventFilter filter = new EventFilter() {
    public boolean accept(XMLEvent event) {
    return event.isStartElement();
    XMLEventReader xmlFilteredEventReader = xmlif.createFilteredReader(xmlEventReader, filter);
    Schema mySchema = getSchema(); // this method retrieves the schema by reading the schema files as
    stream source and calling schemaFactory.newSchema(...)
    Validator validator = mySchema.newValidator();
    validator.setErrorHandler(new SchemaErrorHandler());
    Source xmlSource = new StAXSource(xmlFilteredEventReader);
    validator.validate(xmlSource);
    I get a SAX Parse exception saying "cvc-elt.1: Cannot find the declaration of element 'myElement'"
    And I also see the following exception:
    Caused by: java.lang.NullPointerException
         at com.sun.org.apache.xalan.internal.xsltc.trax.StAXEvent2SAX.bridge(StAXEvent2SAX.java:171)
         at com.sun.org.apache.xalan.internal.xsltc.trax.StAXEvent2SAX.parse(StAXEvent2SAX.java:118)
         at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(TransformerImpl.java:651)
         at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:708)
         at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:313)
         at com.sun.org.apache.xerces.internal.jaxp.validation.StAXValidatorHelper.validate(StAXValidatorHelper.java:89)
         at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorImpl.validate(ValidatorImpl.java:114)
         at javax.xml.validation.Validator.validate(Validator.java:127)
    I am not able to figure out why the validation would work with UnMarshaller but not with StAX.
    Any help appreciated.
    Thanks
    Meera

    Have u tried the Stream STAX parser instead?
    something like:
    SchemaFactory factory = SchemaFactory
                             .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    File schemaLocation = new File(XSD_FILE_PATH);
                   Schema schema = factory.newSchema(schemaLocation);
    // 3. Get a validator from the schema.
    Validator validator = schema.newValidator();
    ErrorHandler lenient = new ForgivingErrorHandler(fw);
    validator.setErrorHandler(lenient);
    XMLInputFactory staxFactory = XMLInputFactory.newInstance();
    staxFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,
                             Boolean.TRUE);
    staxFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,
                             Boolean.FALSE);
    staxFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE,
                             Boolean.TRUE);
    staxFactory     .setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    FileInputStream fis = new FileInputStream(XML_FILE_PATH);
    XMLStreamReader xmlr = staxFactory.createXMLStreamReader(fis);
    validator.validate(new StAXSource(xmlr));

  • Detection of encoding of XML file with the StAX parser

    Hello!
    I am using the StAX parser to read an XML file which can have different encodings.
    I don't know how to detect the encoding before reading the file.
    This is the way I instantiate the reader now:
    XMLStreamReader xmlr = xmlif.createXMLStreamReader(new InputStreamReader (new FileInputStream(inputfile), "utf-8"));
    Is there any way to make the reader detect the encoding with StAX? Is it possible detect the encoding with SAX or DOM?
    Just paste some piece of code and you will help me a lot!
    Thanks,
    Lara

    XML parsers are supposed to auto-detect the encoding of their inputs. The SAX and DOM parsers built into Java, as well as others like Xerces, do that. I don't know whether your StAX parser does, but it should. There is a standard procedure for determining the encoding that is described in the XML spec.
    However if you have malformed XML that fails to declare its encoding properly, then none of those parsers will be able to fix that problem for you.
    Here's the simplified rule as it applies to most files: if the XML file doesn't have a prolog, or if it's prolog doesn't specify an encoding, the parser will assume the file's encoding is UTF-8. If the XML file does have a prolog that specifies an encoding, the parser will assume that encoding.
    Unfortunately it is common for people to write XML files that don't declare an encoding, but to forget to encode the file in UTF-8. Then you have a file that is actually encoded in (e.g.) Windows-1252, but the parser believes it is UTF-8, and this fails when there are non-ASCII characters in the document.

  • SAX support for XML 1.1

    Hi again
    I was searching for a method like setVersion(1.1) on the SAX parser, but I couldn't find any.
    Does anyone know if SAX supports 1.1, and if so then how? Or did I not find it because it doesn't exist..?

    Actually, the SAX and StAX parsers in JAXP 1.4 support XML 1.1.Well, that's interesting to know. I was under the impression that XML 1.1 had been released and completely ignored by users of XML, since I hadn't read a single thing about it for about two years.
    And I must say this idea of people from Sun who actually know what the hell they are talking about coming here and answering questions is a considerable improvement.

  • StAX :streaming API for XML

    hi
    I would like to know about stAX and how it is better over the earlier approaches like SAX and DOM

    http://www.xml.com/pub/a/2003/09/17/stax.html

  • What does StAX stand for?

    I googled about StAX.Some websites told that StAX stands for "Standard API for XML" and some told that "Streaming API for XML Processing"
    What is this right one?

    StAX is specifically for streaming, and there are several parsers which could be described as "standard" (SAX and DOM come to mind). So I will let you figure it out from there.
    By the way I thought you said you were trying to learn XML. This question doesn't help you learn XML, it's really just irrelevant trivia. Knowing the answer won't improve your XML skills in the least. Try to concentrate on the important things.

  • Using Stax

    Hi everyone,
    I'm trying to find out if the J2 SDK supports Stax out of the box.
    So far it seems, that even Java 5 only supports DOM and SAX.
    Is this correct?
    Thanks in advance,
    Paulo Pinto

    Yes, I think StAX will become part of the Java platform in Java 6.0 (Mustang). WSDP 1.6 includes an EA implementation.

  • Xml-sax

    hi all
    i am getting the following error while running a java program...can anyone help me in setting the sax driver...?
    log:
    java.lang.ClassNotFoundException: org.apache.crimson.parser.XMLReaderImpl
         at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(Unknown Source)
         at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(Unknown Source)
         at MySAXApp.main(MySAXApp.java:17)
    Exception in thread "main"
    thanks in advance..!

    log:
    java.lang.ClassNotFoundException:
    org.apache.crimson.parser.XMLReaderImpl
    at
    t
    org.xml.sax.helpers.XMLReaderFactory.createXMLReader(U
    nknown Source)
    at
    t
    org.xml.sax.helpers.XMLReaderFactory.createXMLReader(U
    nknown Source)
         at MySAXApp.main(MySAXApp.java:17)
    Exception in thread "main" That class is found in "rt.jar" in JDK 1.4 onwards. Are you using 1.4 or higher?

  • XML - 0112 Error on parsing using SAX and xml file in InputSource object.

    I need to parse a XML string and extract some information. I have to use SAX parser. I'm converting hte string to InputSource and then trying to parese.
    i'm getting XML-0112 error, my guess is that it is not able to locate DTD file but i tried hardcoding the whole path in DOCTYPE tag.
    i tried doing setSystemId also but no luck.
    null

    Can you post a simple test case to look at?

  • Difference between DOM and SAX

    Difference between DOM and SAX

    a sax parser is event driven meaning it processes the xml as it sees it and then forgets about it.
    you have to implement what you want the parser to do wants it reaches a certain event
    dom on the other hand keeps the whole structure of the message in memory as a tree.
    so there are strengths and weaknesses in both.
    you have to evaluate what you need

Maybe you are looking for

  • Windows 7 on iMac (BootCamp) won't wake up

    I have Windows 7 (32-bit) installed via BootCamp on my iMac Mac OS X 10.6.3. When Windows goes to sleep, it will not wake up. I have to restart the machine & W7 then "resumes". I saw another thread pertaining to his on a notebook, but the driver fix

  • CRM Loyalty Management - Dynamic attributes

    Hi, I am new to loyalty management. I wanted to know what is dynamic attributes which is linked to loyalty programs in loyalty management? I know its theoritical meaning but if any one could explain with an practical example then it would be really h

  • Vim issues...meta keys and colorscheme not working correctly

    The first issue isn't really a vim problem, but it's related.  When running Vim in a terminal, my meta key bindings don't work.  I've tracked it down to a problem with Xfce's Terminal as noted here: http://vimdoc.sourceforge.net/htmldoc/m - p-alt-key

  • Mail Rules Question

    I have a lot of email on my Gmail account. A semi significant portion of them are status updates, such as Facebook, Pownce, Netflix, and other site updates. In the past when I used POP, it wasn't such a big deal to keep these emails because Gmail off

  • Can't figure out how to open program

    I have downloaded the 30 day trial version and it is done installing, but i can not find a program or anything so i can use it.