Using a Parser like SAXParser or DocumentBuilder is much preferred. You can accurately get the tags and process the data. They will be particularly handy when you have many tags to process.
Here is an example of using the Parser to read the body tag:
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler(){
String body = "";
boolean isBody = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("body")) {
isBody = true;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (isBody) {
body = new String(ch, start, length);
System.out.println("body : " + body);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("body")) {
isBody = false;
}
}
};
saxParser.parse(new InputSource(new StringReader("<message id=\"dsds\" to=\"test@test.com\" type=\"video\" from=\"test@test\"><body id=\"dd\">TESTTESTTEST</body><active xmlns=\"http://jabber.org\"/></message>")), handler);