문제

I have to modify some attributes in an XML file with Java. The input XML has all attribute values surrounded with single quotes.

But after making all the changes in the document, when I save the document into a XML file all the attribute values are surrounded by double quotes.

XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.output(doc, new FileWriter(path));

Is there any way that I can make the outputter use single quotes??

Thanks

도움이 되었습니까?

해결책

Technically, yes.... but.... There is nothing semantically different between single and double quotes.... (the resulting document from JDOM is just as valid).... Is there a really good reason why you need to do this? If there is, I would be interested to know, and perhaps introduce it as a 'native' feature of JDOM....

But, you can change the format of it with (only) a little bit of work - 15 lines of code or so... The JDOM2 API in theory makes this a fair amount easier. You can create your own XMLOutputProcessor, using a subclass of the AbstractXMLOutputProcessor and override the printAttribute() method... for example (getting rid of some code paths that your are not likely to need (like non-escaped output):

private static final XMLOutputProcessor CUSTOMATTRIBUTEQUOTES = new AbstractXMLOutputProcessor() {

    @Override
    protected void printAttribute(final Writer out, final FormatStack fstack,
                            final Attribute attribute) throws IOException {

            if (!attribute.isSpecified() && fstack.isSpecifiedAttributesOnly()) {
                return;
            }
            write(out, " ");
            write(out, attribute.getQualifiedName());
            write(out, "=");

            write(out, "'"); // Changed from "\""

            // JDOM Code used to do this:
            //  attributeEscapedEntitiesFilter(out, fstack, attribute.getValue());
            // Now we instead change to quoting the ' instead of "
            String value = Format.escapeAttribute(fstack.getEscapeStrategy(), value);
            // undo any " escaping that the Format may have done.
            value = value.replaceAll(""", "\"");
            // do any ' escaping that needs to be done.
            value = value.replaceAll("'", "'");
            write(out, value);

            write(out, "'"); // Changed from "\""
    }
};

Now that you have this cusome outputter, you can use it like:

XMLOutputter xmlOutput = new XMLOutputter(CUSTOMATTRIBUTEQUOTES);
xmlOutput.output(doc, new FileWriter(path));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top