Is there another way to convert XML Document object to String just like using transform or XmlSerializer from Apache API? I don't want to use mentioned conversion methods because it renders my output xml modifying tags representation ( like collapsing the empty tags to singleton tags). I want conversion method that output in String from the Document object (kind of treating content of Document object as text).
1 Answer
You could do worse than SAX, by extending DefaultHandler2 or DefaultHandler:
class Parser extends DefaultHandler {
StringBuffer sb = new StringBuffer();
public void characters(char[] ch, int start, int length) {
sb.append(new String(ch, start, length);
}
public void startElement(String ns, String qname, String name, Attributes attrs) {
sb.append(qname+": ");
}
public void endElement(String ns, String qname, String name) {
sb.append("\n");
}
public String toString() {
return sb.toString();
}
}
3 Comments
kdgregory
Have you actually run this code? Can you describe what the output looks like?
hd1
Many, many times in fact, @kdgregory... if you add a main function that calls the SAXParser according to the documentation at xml.org, it outputs only the text from any XML document, when you print your instance variable to the console.
Vix
@hd1, I need xml tags also in the output string not just text nodes from my xml
Document.
<tag></tag>and<tag/>then it's broken. According to the spec, both forms are acceptable, with identical effect.