views:

20

answers:

1

Hi,
maybe this is a n00b-question.

I try to parse an xml-file like that:

<?xml version="1.0" encoding="UTF-8" ?>
<test>
  <a></a>
</test>

with the following code:

public static void parse(File f) {
    final DefaultHandler handler = new DefaultHandler() {
        @Override
        public void processingInstruction(String target, String data) throws SAXException {
            System.out.println("Processing Instruction");
        }
    };
    SAXParserFactory.newInstance().newSAXParser().parse(f, handler);
}

I expect the output "Processing Instruction" to be printed on stdout. But this doesn't happen. Can somebody tell me why?

+1  A: 

From JavaDoc:

A SAX parser must never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method.

As I understand it, the <?xml version="1.0" encoding="UTF-8" ?> line will not be reported/catched by this method. Try to add another processing instruction in the xml code and feed it to the parser again.

Andreas_D
Thanks for the answer. Another question then: Is it possible to find out if there is a valid xml declaration in the file?
Martin
@Martin: ISTR that it'll throw an exception if the declaration isn't valid.
Vinko Vrsalovic
In other words, a xml declaration is not a processing instruction and must not be reported by the parser as one.
Jörn Horstmann
@Vinko Unfortunately it doesn't throw an Exception if the declaration is missing...
Martin
@Martin: But it does if it's invalid, no?
Vinko Vrsalovic
@Vinko That's true. :-)
Martin