Domanda

When I create a jdom document (Document doc = new Document();), by default I only see version and encoding in the xml header:

<?xml version="1.0" encoding="utf-8" ?>

How can I add the standalone attribute to get:

<?xml version="1.0" encoding="utf-8" standalone="no" ?>
È stato utile?

Soluzione

The Header is normally stripped by the XMLParser before the document gets to JDOM. I'm pretty sure you mean you're looking at the output from JDOM, which adds the XML declaration back in.

You can adjust how the XML Declaration is processed by creating a custom XMLOutput processor... with this custom class, override the printDeclaration method and change it to do what you need....

public static final XMLOutputProcessor XMLOUTPUT = new AbstractXMLOutputProcessor() {
    @Override
    protected void printDeclaration(final Writer out, final FormatStack fstack) throws IOException {
        write(out, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?> ");
        write(out, fstack.getLineSeparator());
    }
};

Then, when you want to use this, you pass it to your XMLOutputter as:

XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat(), XMLOUTPUT);
xout.output(doc, System.out);

It is apparent that the mechanism for doing this is rather cumbersome. I will look in to what alternatives there are, and perhaps fix this in a future version.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top