Use an XMLParser
(check this page), one that works nicely is the XmlPullParser.
You can initialize your parser with:
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
Than you can iterate over the complete XML
object using
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
/*YOUR CODE HERE*/
eventType = xpp.next();
}
Where you can check for the eventTypes
: START_DOCUMENT
, START_TAG
, END_TAG
, and TEXT
.
Once you are in either start or end tag you can get the name of the tag using getName()
, at the TEXT
event type you can use getText()
and you can use, at the BEGIN_TAG
, the functions getAttributeCount()
, getAttributeName(index)
and getAttributeValue()
you can get all the attributes belonging to each tag.
In your specific case
You can use something like this:
String xmlString = YOURSTRING_HERE;
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( xmlString ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
if (xpp.getName().equals("PrintLetterBarcodeData")){
for (int i=0; i<xpp.getAttributeCount(); i++){
System.out.println("attribute:"+xpp.getAttributeName(i)+" with value: "+xpp.getAttributeValue(i))
//Store here your values in the variables of your choice.
}
}
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");