4

I try to parse an XML and get the following error, what could the problem be?

I/System.out(8058): Wrong XML file structure: Unexpected token (position:TEXT @1:2 in java.io.StringReader@4113db88)

Thats the method I parse with

public final static Document XMLfromString(String xml){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }

    return doc;

}

And thats the XML I try to parse:

<?xml version="1.0" encoding="UTF-8"?>
<app>
    <Date Value="02.07.2012">
     </Date>
</app>
Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
  • Try looking here, same question. http://stackoverflow.com/questions/7870593/android-parsing-error-on-tablet-but-not-emulator it seems to be due to a difference in charset between your device and the xml – Jon Taylor Jul 05 '12 at 09:33
  • Thank you for you answer. How can I find out what the charset of the device is? – Bruno Bieri Jul 05 '12 at 10:02
  • 1
    Please see the answer for the [similar question](http://stackoverflow.com/questions/15254089/kxmlparser-throws-unexpected-token-exception-at-the-start-of-rss-pasing). In gist- there are some invisible byte marks that choke the pull parser – Bostone Mar 12 '13 at 18:30
  • @BrunoBieri I am struggling with the exact same problem. How did you solve it? could you provide the solution in an edit? – The Dude Apr 10 '15 at 10:17

2 Answers2

1

That seems like it doesn't like the question mark. Can you make sure that you save the XML file with the correct encoding? (UTF-8)

Zoltán
  • 21,321
  • 14
  • 93
  • 134
1

Your java string is in an UTF-16 encoding be default. To create Document using string try this:

Document doc = db.parse(new ByteArrayInputStream(xmlData.getBytes())); 
pleerock
  • 18,322
  • 16
  • 103
  • 128
  • Thanks for your answer. Unfortunately the project is already finished and I can't go back to change that. – Bruno Bieri Oct 11 '12 at 08:17
  • 1
    yes, I understood. But maybe someone else will face with the same problem and it help him. Because I faced with this and found solution – pleerock Oct 11 '12 at 08:43