0

I the following snippet of XML without any parent node

<Message>
<Header>
<ID>1234</ID>
<Name>xxxx</Name>
</Header>
</Message>

<Message>
<Header>
<ID>4567</ID>
<Name>YYYY</Name>
</Header>
</Message>

<Message>
<Header>
<ID>6789</ID>
<Name>zzzz</Name>
</Header>
</Message>

I'd like extract only the data contained with the Name tags. How is this possible?

1 Answer 1

1

You can use SAXParser to parse your all names as follows...

public class NameXMLParser extends DefaultHandler {

    List<String> nameList = new ArrayList<String>();

    private boolean isName = false;
    private StringBuffer mBuffer = new StringBuffer();

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException {

        if (localName.equalsIgnoreCase("Name")) {
            isTitle = true;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {

        if (isName) {
            mBuffer.append(new String(ch, start, length));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        if (localName.equalsIgnoreCase("Name")) {

            nameList.add(mBuffer.toString());
            isTitle = false;
            mBuffer.delete(0, mBuffer.length());

        }

    }

    public List<String> getNameList() {

        return nameList;
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.