Search code examples
xml-parsingdom4j

Parsing response.getEntity(String.class) string to xml with DocumentHelper.parseText() in dom4j


dom4j has no trouble doing

String text = "<person> <name>James</name> </person>";
Document document = DocumentHelper.parseText(text);

What I need is this

String text = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"+
"<person> <name>James</name> </person>";
Document document = DocumentHelper.parseText(text);

But it throws an exception.

org.dom4j.DocumentException: Error on line 1 of document  : parsing initialization error: org.gjt.xpp.XmlPullParserException: only whitespace content allowed outside root element at line 1 and column 1 seen 

Solution

  • I find the problem. The before line below is the one that fails. The after line works.

    BEFORE

    Document output = DocumentHelper.parseText(response.getEntity(String.class));
    

    AFTER

    Document output = DocumentHelper.parseText(response.getEntity(String.class).trim());