Hello Hello - 17 days ago 5
Java Question

How to get the whole text of StAX XMLEvent object?

I am using StAX Iterator api to read an xml.

XML:

<FormData OID="QUAL">
<IGData IGRepeatKey="1" IGOID="SQUAL" TType="Insert">
<IData Value="0859" IOID="SID"></IData>
<IData Value="DM" IOID="RDOMAIN"></IData>
</IGData>
<IGData IGRepeatKey="1" IGOID="SQUAL" TType="Insert">
<IData Value="0860" IOID="SID"></IData>
<IData Value="2013-01-03T02:00" IOID="QVAL"></IData>
</IGData>
</FormData>


And Stax code:

while(xmlEventReader.hasNext()){
xmlEvent = xmlEventReader.nextEvent();
eventString = xmlEvent.toString();
if(xmlEvent.isStartElement() && eventString.contains("FormData") && eventString.contains("QUAL")){
//do something
}


}

It is working (eventString has whole text of xmlEvent) in my local environment.

But when i deploy this into server, eventString contains like "Stax Event #1". So if condition is returning false.

I thought both are using different XMLEvent implementations. So i checked it through code, and jar is same in both environments: jre1.8.0_73/lib/rt.jar!/javax/xml/stream/events/XMLEvent.class

How to get the whole text of XMLEvent object? Am i doing anything wrong here? Please suggest any other alternatives.

Answer

Every XML Event has 3 states

  1. Start Element
  2. is Characters
  3. End Element

for eg if you need to access the data for " IGRepeatKey " from your xml file then in the state ( Start Element ), you need to check if IGData tag has started , if its true . Start a new Iterator which will iterate over all the tags i.e IGRepeatKey , IGOID , TType .

Try Something like this

Iterator<Attribute> iterator = element.getAttributes();
while (iterator.hasNext())
{
  Attribute attribute = (Attribute)iterator.next();
  QName name = attribute.getName();
  String value = attribute.getValue();
  System.out.println(name+" + "+value);
}

Add this iterator in xml.isStartElement() block .