Question

Here is my sample code

<myElement>  </myElement>

I try to take the above node value as few spaces into java variable, but it gives me an empty string variable.

How can I read the contain of xml node as white space

Was it helpful?

Solution

I am not 100% sure, but maybe this helps you.

Presume you have an XML like this

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <myElement>  </myElement>
</root> 

As you didn't tell what you're using, I made an example in SAX. Just be aware that is not the fastest way if you have a huge XML to read.

public class Test {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        DefaultHandler myHandler = new MyHandler();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(new File("empty.xml"), myHandler);
    }
}

The HandlerClass for your Callbacks:

public class MyHandler extends DefaultHandler {
    private boolean isEmpty = false;
    private String  fewSpace;

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    if (this.isEmpty) {
        this.fewSpace = " ";
        System.out.println(qName + this.fewSpace + " :)");
        this.isEmpty = false;
    }
}

@Override
public void characters(char[] buffer, int offset, int length) throws SAXException {
    String s = new String(buffer, offset, length);

    if (s.matches("\\s {1,}")) {
        System.out.println("This Element has empty String");
        this.isEmpty = true;
    }
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top