Java – Handling Empty Tags in XML using Sax Parser, Java

javasaxsaxparserxml

I'm Using a Sax parser to handle a pre-written XML file….i have no way of changing the XML as it is held by another application but need to parse data from it. The XML file contains a Tag
< ERROR_TEXT/>
which is empty when no error is occurred.
as a result the parser takes the next character after the tag close which is "\n".
I have tried
result.replaceAll("\n", "");
and
result.replaceAll("\n", "");

how do I get SAX to recognize this is an empty tag and return the value as "" ?

Best Answer

You DO THAT. If you have xml and Java source blow.

<ERROR_TEXT>easy</ERROR_TEXT><ERROR_TEXT/>

Java code

private boolean isKeySet = false;
private String key = "";
@Override
public void characters(
    char[] ch,
    int start,
    int length
) throws SAXException
{
    if (!isKeySet) {
        return;
    }
    isKeySet = false;
    logger.debug("key : [" + key + "], value : [" + value + "]");
}
@Override
public void startElement(
    String uri,
    String localName,
    String qName,
    Attributes attrs
) throws SAXException
{
    key = qName;
    isKeySet = true;
}

@Override
public void endElement(
    String uri,
    String localName,
    String qName
) throws SAXException
{
    if (isKeySet) {
        isKeySet = false;
        logger.debug("key : [" + key + "](EMPTY!!!)");
    }
}

RESULT log:

key : [ERROR_TEXT], value : [easy]

key : [ERROR_TEXT](EMPTY!!!)

Call flow: startElement() -> characters() -> endElement() -> startElement() -> endElement() -> characters()

That's it! THE END