0

I am trying to parse a string representation of a xml document with jdom2. I expect the xml string

<?xml version=\"1.0\" encoding=\"UTF-8\"?>

to be a valid xml document. But when I run this simple code snippet:

import java.io.IOException;
import java.io.StringReader;
import org.jdom2.*;

public class Main {
    public static void main(String []args){
        SAXBuilder parser = new SAXBuilder();
        String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        try { 
            Document doc = parser.build(new StringReader(data));
        } catch (JDOMException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

I receive the error:

org.jdom2.input.JDOMParseException: Error on line 1: Premature end of file.
    at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:232)
    at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:303)
    at org.jdom2.input.SAXBuilder.build(SAXBuilder.java:1196)
    at testpack.Main.main(Main.java:32)

Does the xml specification not allow an xml payload without an root element? If not, how should I check if the xml document is empty?

Edit: I also noticed that the documentation in Jdom2 for the Document() class states that

A document must have a root element, so this document will not be well-formed and accessor methods will throw an IllegalStateException if this document is accessed before a root element is added.

It might just be that Jdom2 doesn't support empty xml documents?

3
  • An .xml file with length 0 would seem the best definition of "empty XML file." Commented Jan 18, 2018 at 15:46
  • @JoopEggen That would exclude an .xml with an valid header, such as the case presented in my question. Commented Jan 18, 2018 at 15:48
  • Just a note: my xml string was received from a remote server application and it could be the source of the document that is the problem Commented Jan 18, 2018 at 16:02

1 Answer 1

1

After further investigation I have noted that the specification for and xml document as defined by w3 specifies that a 'Well formed xml document' should adhere to

It contains one or more elements.

Meaning zero elements is not an option. The input xml String is a malformed xml string.

Sign up to request clarification or add additional context in comments.

Comments

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.