create xml with jdom, how to set standalone=“no” attribute

廉价感情. 提交于 2019-12-01 04:12:33

问题


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" ?>

回答1:


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.



来源:https://stackoverflow.com/questions/21170732/create-xml-with-jdom-how-to-set-standalone-no-attribute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!