0

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).

2
  • 1
    You could write your own serializer... but that's a lot of work. If your downstream processor cares about the difference between <tag></tag> and <tag/> then it's broken. According to the spec, both forms are acceptable, with identical effect. Commented Dec 20, 2012 at 1:22
  • 1
    Your request doesn't make sense. A DOM Document object doesn't have a "tag representation". Any method of serializing a DOM Document is going to have to devise a representation, there is no existing representation to preserve. Commented Dec 20, 2012 at 8:32

1 Answer 1

1

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();
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Have you actually run this code? Can you describe what the output looks like?
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.
@hd1, I need xml tags also in the output string not just text nodes from my xml Document.

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.