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.

Similar Messages

  • Creating XML from a POJO using StAX

    Hi Experts,
    I have a POJO and now want to create an XML which has the elements as that of the POJO using StAX.
    Can anybody please help me out.
    Thanks in advance.

    swati_pekam wrote:
    Yes I totally agree with you, had initially used JAXB....however client needs StAX to be used.. :(What? Why?
    Do you mean "client" as in "client side program"?
    In that case, the requirement is bullshit, because the receiving end of the XML doesn't know which technology is used to create it.
    Do you mean "client" as in "the people who pay me to do that"?
    In that case, the requirement is bullshit, because they should not force you to use tools that are not fit for the task ..
    Please clarify this requirement. Why exactly do you think (or does the client think) that you need to use StAX?

  • Help with simple XML reading example using StAX

    Please, could somebody help me with this issue?
    Or, could somebody point me to a comprehensive StAX tutorial?
    thanks!
    I have prepared a simple sample that looks like 'homework', but this newbie task is getting me crazy...
    I just want to store in the object Shop[] shopsArray; the next XML file, using StAX:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <shops>
        <shop>
             <name>Amazon</name>
            <code>AMZ</code>
            <url>www.amazon.com</url>
            <product>
                <book>
                    <name>Core JSF</name>
                    <code>cojsf</code>
                    <price>136</price>
                    <pages>333</pages>
                </book>
            </product>
            <product>
                <book>
                    <name>Java forr Dummies</name>
                    <code>jfd</code>
                    <price>68</price>
                    <pages>400</pages>
                </book>
            </product>
            <product>
                <video>
                    <name>Braveheart</name>
                    <code>brvh</code>
                    <price>15</price>
                    <duration>3h</duration>
                </video>
            </product>
        </shop>
         <!-- <shop>Other types of shops</shop> -->
    </shops>Having the related classes below:
    public class Shop {
         String name;
         String code;
         String url;
         Product[] productsArray;
    public class Product {
         String name;
         String code;
         String price;
    public class Book extends Product {
         String pages;
    public class Video extends Product {
         String duration;
    }

    [http://vtd-xml.sf.net|http://vtd-xml.sf.net] While I am not an expert on StAX, I think you may be interested in vtd-xml to simplify coding as it
    supports random access and XPath
    http://vtd-xml.sf.net

  • Using StAX with xslt transformations in the right way?

    Hi!
    What do I need to enable the stax functionality to transformations, and which transformer implementations is supporting this? (or is the implementation irrelevant)
    I have made the following to create a StaxSource, but is it enought?
    ---8<---
    private static XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        InputStream xmlInputStream = xmlUrl.openStream();
        XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader( xmlInputStream );
        Source xmlSource = new StAXSource( xmlStreamReader );
    transformer.transform(xmlSource, new StreamResult(writer));
    ---8<---I'm using:
    org.apache.xalan.processor.TransformerFactoryImpland every thing seems to work very nice, but I'm not sure if I have done it in the right way and if it's something that I miss.
    If I understand it correct normal transformations is transforming the xml to a Dom-tree but with StAX it shouldn't and be more memory efficient.
    So anyone have any comments?
    /Per

    Indeed, as DrClap has already stated, using a StAXSource will not guarantee streaming. All of the mainstream XSLT processors build some sort of DOM structure internally because, in the general case, XSLT requires random access on the input document. The only exception to this is the identity transform, which in most processors is done in streaming fashion --i.e., without actually creating an intermediate structure.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Using Stax XMLStreamReader on fragments?

    Im trying to use XMLStreamReader to parse small XML fragments that are streamed from a server to a client.
    Sometimes the fragments refer to namespaces that are defined outside the fragment and XMLStreamReader
    throws an Exception:
    *Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,18]*
    Message: http://www.w3.org/TR/1999/REC-xml-names-19990114#ElementPrefixUnbound
    Is there any way to define the namespaces and their prefixes programmatically? I dont want to disable validation.

    To answer myself. Found out that I can disable namespace awarenes without disabling all validation:
         inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);Would still rather like to define the namespaces..

  • Use of StAX

    I tried to use StAX to modify a big XML file and I used the example EventProducerConsumer to start, as it implemented the same process I needed.
    After some strange random failures I discovered that for big files you cannot use a FileInputStream to read the Xml file, as in the example (at leas in a Windows environment) . Using a FileReader I was able to process quickly a many big files (the dimension is limited only by the heap).
    I don't know if in this was already noticed, as the FileInputStream works fine for small/medium sized file. So, just in case ......
    Marco Pancotti

    I tried to use StAX to modify a big XML file and I used the example EventProducerConsumer to start, as it implemented the same process I needed.
    After some strange random failures I discovered that for big files you cannot use a FileInputStream to read the Xml file, as in the example (at leas in a Windows environment) . Using a FileReader I was able to process quickly a many big files (the dimension is limited only by the heap).
    I don't know if in this was already noticed, as the FileInputStream works fine for small/medium sized file. So, just in case ......
    Marco Pancotti

  • Read only part of a document with Stax

    Hi,
    I have some huge documents (~5GB) and I use Stax to read them.
    My problem: I want to load only a part of the document.
    I know the location that I should put the inputStream, so I skip half of the file.
    Then I push data using xmlReader.hasNext(). After the first iteration though, I get the exception ->
    javax.xml.stream.XMLStreamException: ParseError at [row,col]:[34,4]
    Message: The markup in the document following the root element must be well-formed.
    The original xml is like that:
    <root>
    <element id=1>
    </element>
    <element id=2>
    </element>
    <element id=3>
    </element>
    </root>And I pass to the xmlStreamReader
    <element id=2>
    </element>
    <element id=3>
    </element>So, I know why I get it. Because I include in the input stream only a part.
    When it tries to read the element with id=3 , it says not well formed document.
    which on one hand is correct, but on the other hand not important for me.
    any possible solutions? How to disable the check of xmlstream reader or I don't what.
    no, I cannot wrap a part of a 5Gb file to something else...That's not the point. It will be to slow...
    That why I want to skip so much data in first place, to make it quick.
    The problem is so annoying and a little bit stupid.
    A solution would be to write my own parser, instead of using the XMLStreamReader, but then again, this is stupid, dirty, and duplicate of efforts...
    -------part of the code--------
    FileInputStream inputStream = new FileInputStream(filename);
    inputStream.skip(skipBytes);
    xmlReader = xmlif.createXMLStreamReader(filename, inputStream);
            while (xmlReader.hasNext() && parsingComplete == false) {
                xmlReader.next();
                if (xmlReader.isStartElement()) {
                    parseStartElement(xmlReader);
                    continue;
            }Thanks for the help and any opinions.
    Andreas

    Following the tip about creating a new input stream, I've create a class that extends the FileInputStream, and now it works.
    Extending just the InputStream was really slow. (remember the documents are huge "string" files)
    The code:
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    RootElementAppenderFileInputStream skippedInputStream = new RootElementAppenderFileInputStream(file, skipBytes);
    xmlReader = xmlif.createXMLStreamReader(file.getAbsolutePath(), skippedInputStream);
    while (xmlReader.hasNext() && parsingComplete == false) {
        xmlReader.next();
        if (xmlReader.isStartElement()) {
            parseStartElement(xmlReader);
    public class RootElementAppenderFileInputStream extends FileInputStream {
        private ByteArrayInputStream rootElemStreamStart;
        private boolean readingRoot = true;
        public RootElementAppenderFileInputStream(File file, long skipBytes) throws FileNotFoundException, IOException {
            super(file);
            this.rootElemStreamStart = new ByteArrayInputStream("<O>".getBytes());
            this.skip(skipBytes);
        public int read() throws IOException {
            if (readingRoot) {
                int result = rootElemStreamStart.read();
                if (result == -1) {
                    readingRoot = false;
                } else {
                    return result;
            return super.read();
    }

  • Character encoding problems with weblogic stax implementation?

    Hello all,
    While using Stax to parse some XML, we encounter the following exception when the processor reaches the UTF-8 character C3 B1, ('ñ'):
    Caused by: Error at Line:1, token:[CLOSETAGBEGIN]Unbalanced ELEMENT got:StudentRegistration expected:LastName
    at weblogic.xml.babel.baseparser.BaseParser.parseSome(BaseParser.java:374)
    at weblogic.xml.stax.XMLStreamReaderBase.advance(XMLStreamReaderBase.java:199)
    We suspect that the processor's encoding might somehow be set to ANSI instead of UTF-8. I have read, in other posts, of a startup property related to web services:
    -Dweblogic.webservice.i18n.charset=utf-8
    However, this XML is not a web service request, but rather a file being read from disk after an MDB's onMessage() method is called.
    Could this setting be affecting stax parsing outside of webservices? Any other ideas?
    Thanks!

    As far as I know, we don't support changing outbound message encoding charset in 9.x. Both 8.x and 10.x support it. Check [url http://docs-stage/wls/docs100/webserv/client.html#wp230016]here

  • Using XML to persist data

    Im developing a small application and choosed to use XML instead of MySql because it's smaller and do not require to install a database on the client after software distribution.
    The strategy was not keep all data in the XML file, so some parts are shared over folders.
    Example:
    Let's say I have 10 logins (remember that login can't be repeated) so I have 10 foldes (packges) eah one with it's on xml file about the login info.
    So far, it's working very fast.
    The problem is that I don't know what parser (read/write) to use.
    1)
    There's a lot over the web, but I'm affraid abaout memory and application size (I'd like to keep it small and readable later) ... so should I use Suns DOM or Stax?
    2)
    There are simple things I really need: read the xml, change it if needed and display the data. So I need to populate my objects, change them and persist again. Also, I'd like to persist only the nodes that were actualy changed, keeping the unchanged data.

    No 1.
    First of all, let me apologize. I kinda lost myself on my own explanation! Sorry.
    No. 2.
    .....Yeah, I ended up finding an easy way to read those small xml files (the way I'm trying to keep them so far)...You're right, could be even SAX or DOM. I've choosed SAX by now.
    .....The big problem was to understand all those acronyms over the web...beyond learning Java, XML we must remember all those words too. Not an easy task.
    No. 3.
    Can anyone tell me EXACTLY how to use StaX ? Cause I will have to use it later by some xml on demand files i'll need to work with.
    No. 4.
    As I've choosed SAX, how do I change only the tags that matter on the xml file? Is it possible?
    Thaks a LOT for all the patient people from this forum.... You are the BEST

  • 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

  • Urgent - Query on STAX

    Hi All,
    I started learning and working with STAX- api (Iterator)
    My requirement is providing the implementation to the methods like
    writeElement
    writeStartElement
    How can i use STAX inorder to implement the above methods.
    Also can anyone provide the implementation classes for the interfaces in the STAX-api.jar (source code)
    Thanks in Advance.

    I think, it is possible to create a query only on Active table but not on Change log table. But why do you want to create on CL table?
    Edited by: Arun Bala G on Feb 7, 2012 7:01 PM

  • XML StAX - How to extract text and elements?

    Hello,
    I'm using StAX to parse this XML document (heavily reduced):
    <?xml version="1.0" encoding="utf-8"?>
    <html>
      <head>
        <title>Foo</title>
      </head>
      <body>
        <p>loading ...</p>
      </body>
    </html>I need to extract the data between the <body> element i.e "<p>loading...</p>". My problem is that I can only find methods that extracts the text and not the elements. Is there an easy way to do this using the XMLStreamReader instance, or do I have to use another class?
    Thanks

    Thanks for your reply. But does that really mean that I have to create my own method, which will collect both text and elements information in a StringBuffer as I parse through the enclosing element? I just think it is strange that there isn't a convenient method to extract all data (text & elements) between one element.
    Something like this?:
    private void handleBody(XMLStreamReader parser,XMLEventAllocator allocator) throws XMLStreamException {
              StringBuffer body = new StringBuffer();               
              while(true){
                   String value = null;
                   parser.next();               
                   if (parser.getEventType() == XMLStreamConstants.START_ELEMENT){
                        String name = parser.getLocalName();
                        if (!name.equalsIgnoreCase("body")){
                             StartElement startElement = getXMLEvent(allocator,parser).asStartElement();                         
                             value = startElement.toString();
                   else if (parser.getEventType() == XMLStreamConstants.END_ELEMENT){
                        String name = parser.getLocalName();
                        if (name.equalsIgnoreCase("body")){
                             break;
                        else{                         
                             EndElement endElement = getXMLEvent(allocator,parser).asEndElement();                         
                             value = endElement.toString();
                   else if (parser.hasText()){                    
                        value = parser.getText();
                   if (value != null){
                        body.append(value);               
         }

  • StAX and large XMLs

    Hi everyone,
    I want to use StAX for parsing an XML file that is about 20 MB large. Within this XML, a binary file is embedded which is located under a specific XML element.
    I thought that it would be a good idea to use StAX in that situation, because I want to make use of streaming technology. One goal was to avoid that I have the entire content of the embedded file in memory, but only single characters, which I can put into another stream.
    I am now facing the problem, that the StAX implementations (I tested the BEA implementation and the reference implementation) do not support the "getTextCharacters" method, which would be the most essential method for retrieving characters from a stream during a "CHARACTER" event.
    Currently, the only possibility to read out characters is calling the "getText" method, but in that case, I have the entire file in memory (really bad!).
    Does anyone has experience using StAX and especially streaming large XML elements to a file?
    I see no benefit of a StAX implementation which does not allow calling this method:
    getTextCharacters(int sourceStart,char[] target,int targetStart, int length)
    In my opinion, that would be the actual heart of a real streaming API.
    Does anyone know a good StAX implementation that supports that operation?
    Best regards,
    Martin

    In general, controlling this isn't easy, you may try using writeEmptyElement() but I don't believe it makes any guarantees about how closing tags are serialized.
    If large data sets is a big problem in your application, and readability isn't a primary concern, you may try using Fast Infoset,
    https://fi.dev.java.net
    which is now part of the platform in JDK 6. Using this format you can improve your application's performance and reduce bandwidth requirements by half, without having to re-write your application. For example JAX-WS, the WS API, already supports this format. Morever, it includes an HTTP-based content negotiation algorithm to make the use of the format completely transparent.

  • StAX  XMLStreamReader  getTextCharacters() problem withj long strings

    Hi,
    I am reading long hexidecimal strings that are within elements in xml using StAX and with long hexidecimal strings I seem to be losing the end of these strings. I am creating XMLStreamReader and I tried using getText() and this was not returning anything but using getTextCharacters() seems to work until I get these long strings. Here is the code I am using for processing a CHARACTERS event:
    import javax.xml.stream.XMLInputFactory;
    import javax.xml.stream.XMLStreamConstants;
    import javax.xml.stream.XMLStreamException;
    import javax.xml.stream.XMLStreamReader;
    if(event == XMLStreamConstants.CHARACTERS){
    int start = reader.getTextStart();
    int length = reader.getTextLength();
    char[] textCharacters = reader.getTextCharacters();
    String text = (new String(textCharacters,start,length)).trim();
    int containsHexInt = text.indexOf("0x");
    if(currentElement.equals("attrid")){
    attributeIdString = text;
    }else if(currentElement.equals("symbol")){
    symbolString = text;
    }else if(currentElement.equals("value") && containsHexInt != -1){
    if(transactionsTimeStamp==null){ transactionsTimeStamp=DateUtil.getNowInAcFormat();
    if(staxCompoundsDocument == null){
    staxCompoundsDocument = new StAXCompoundsDocument(
    outputFileName, transactionsTimeStamp, exlusionFilePath );
    staxCompoundsDocument.outputDocumentHead();
    staxCompoundsDocument.addCompound(transTimeStamp,fileTrans,
    symbolString,attributeIdString, parseHex(text),state,userid);
    I am using jsr173_api.jar though I don't have the version number for this.
    If anyone could help me explain this it would be real help. I am guessing it may be down to using buffers under the covers for StAX but don't know exactly how this works.
    Thanks in advance
    Rob

    Thanks DrClap,
    that was the problem, having not worked with StAX before I didn't know it could behave like this :(
    So I had a look at the documentation and tried setting the IS_COALESCING property but it seems the implementation of StAX that we have doesn't support this :( and doesn't have the methods isCoalescing :( and I don't have enough influence to change that.
    So I have had to set up my looping through events like the following pseudo code :
    if event != CHARACTERS && stringBuffer.length > 0
    process characters
    make stringBuffer empty
    do some event processing
    if event == CHARACTERS
    add the characters to the string buffer
    If there is a better way of doing this I'd like to know but at least I have something that works at the moment.
    Thanks
    Rob

  • StAX getTextCharacters error

    Hi I am reading long hexidecimal strings that are within elements in xml using StAX and with long hexidecimal strings I seem to be losing the end of these strings. I am creating XMLStreamReader and I tried using getText() and this was not returning anything but using getTextCharacters() seems to work until I get these long strings. Here is the code I am using for processing a CHARACTERS event:
    import javax.xml.stream.XMLInputFactory;
    import javax.xml.stream.XMLStreamConstants;
    import javax.xml.stream.XMLStreamException;
    import javax.xml.stream.XMLStreamReader;
    if(event == XMLStreamConstants.CHARACTERS){
    int start = reader.getTextStart();
    int length = reader.getTextLength();
    char[] textCharacters = reader.getTextCharacters();
    String text = (new String(textCharacters,start,length)).trim();          
    int containsHexInt = text.indexOf("0x");
    if(currentElement.equals("attrid")){
    attributeIdString = text;
    }else if(currentElement.equals("symbol")){
              symbolString = text;
    }else if(currentElement.equals("value") && containsHexInt != -1){
    if(transactionsTimeStamp==null){                transactionsTimeStamp=DateUtil.getNowInAcFormat();
    if(staxCompoundsDocument == null){
    staxCompoundsDocument = new StAXCompoundsDocument(
         outputFileName, transactionsTimeStamp, exlusionFilePath );     
    staxCompoundsDocument.outputDocumentHead();
    staxCompoundsDocument.addCompound(transTimeStamp,fileTrans,
    symbolString,attributeIdString, parseHex(text),state,userid);
    I am using jsr173_api.jar though I don't have the version number for this.
    If anyone could help me explain this it would be real help. I am guessing it may be down to using buffers under the covers for StAX but don't know exactly how this works.
    Thanks in advance
    Rob

    WE received the following error:
    ARP_STAX_121 invalid after applying patch FIN_PF.G.
    Metalink note 5209321 suggests workaround but the problem is we have got around 40 operating units, we need to do it manually for all of them. I am wondering is there any single script so that we can run it from the backend to resolve the issue.
    Do you get the same error in the doc when you compile the package? If yes, and you still need the script then you have to contact Oracle support for the fix.
    Thanks,
    Hussein

Maybe you are looking for

  • Why does any file over 2gb just list as 2.0gb and downloads imcomplete?

    When i try to download my exercise files from a website, firefox or Waterfox just says 2.0gb and will download with no errors.When i try to unzip file,Winrar says its incomplete.I am using windows 7 64 bit and NTFS formatted drive.This also happens i

  • Orientation issues when using Save As in Adobe Reader X

    I am using Adobe Reader X (10.1.2) and any time I change the orientation of the PDF file, when I do FILE - SAVE AS - PDF and save the PDF under a different name, and then OPEN the newly created PDF, the orientation reverts back. I have uninstalled an

  • Message not coming to Receiver system - File to RFC

    I have a small problem in File to RFC connection. We are trying to create a PO using a BAPI. In the XI system , it shows the XML is processed successfully but PO is not generated in the R/3 system. Is there any way to check whether the message has co

  • Port 995

    Hi, I have just set up web hosting and I am attempting to set-up my email so that it can be received and sent from Mail. I have been in constant correspondence with their support desk, but they don't seem to be able to assist any further. They tell m

  • Operator - and =

    hello everybody i wanted to ask what's the diffrence between the -> operator and the => operator thank you amit