Read XML String using StAX

前端 未结 4 1598
天命终不由人
天命终不由人 2020-12-31 13:51

I am using stax for the first time to parse an XML String. I have found some examples but can\'t get my code to work. This is the latest version of my code:



        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 14:11

    I faced a similar issue as I was getting "IllegalStateException: Not a textual event" message When I looked through your code I figured out that if you had a condition:

    if (event == XMLStreamConstants.START_ELEMENT){
    ....
    addressId = reader.getText(); // it throws exception here
    ....
    }
    

    (Please note: StaXMan did point out this in his answer!)

    This happens since to fetch text, XMLStreamReader instance must have encountered 'XMLStreamConstants.CHARACTERS' event!

    There maybe a better way to do this...but this is a quick and dirty fix (I have only shown lines of code that may be of interest) Now to make this happen modify your code slightly:

    // this will tell the XMLStreamReader that it is appropriate to read the text
    boolean pickupText = false
    
    while(reader.hasNext()){
    
    if (event == XMLStreamConstants.START_ELEMENT){
       if( (reader.getLocalName().equals(STATUS) )
       || ( (reader.getLocalName().equals(STATUS) )
       || ((reader.getLocalName().equals(STATUS) ))
             // indicate the reader that it has to pick text soon!
         pickupText = true;
       }
    }else if (event == XMLStreamConstants.CHARACTERS){
      String textFromXML = reader.getText();
      // process textFromXML ...
    
      //...
    
      //set pickUpText false
      pickupText = false;
    
     }    
    
    }
    

    Hope that helps!

提交回复
热议问题