1

I have a recent problem with subsequent spaces. Im appending a text with subsequent spaces , to an XML element. the toXML method of Xom works fine but Writing thruogh a ByteArrayOutputStream with a Serializer is shrinking the spaces.

String textWithMultipleSpaces=" a  b   c ";
Element el=new Element("foo");
el.appendChild(textWithMultipleSpaces);
Document doc=new Document(el);

ByteArrayOutputStream out = new ByteArrayOutputStream();
Serializer serializer = new Serializer(out);
serializer.setIndent(indent);
serializer.setMaxLength(maxLength);
serializer.write(doc);
System.out.println(doc.toXML());
//<foo> a  b   c </foo>
System.out.println(out.toString());
//<foo> a b c </foo>

The subsequent spaces are shrinking to a single one. I cant find the reason

NOT: I see that the Xom Serializer is removing those whitespaces just because i use indent and setMaxLength. Is there a serializer that doesnt touch the text and do just indentation ?

4

1 回答 1

0

我改为使用的解决方案是替代解析器 ( Jsoup ) 来编写输出。这对我有用,可以在属性中保留空白。

但是,此解决方案将所有节点/属性转换为小写。

public static void writeXML(final File xmlFile, final Document doc) {

    BufferedWriter xmlWriter = null;

    try {
        xmlWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmlFile),
                "UTF-8"));
        xmlWriter.write(Jsoup.parse(doc.toXML(), "", Parser.xmlParser()).toString());

    } catch (final IOException e) {
        e.printStackTrace();

    } finally {
        if (xmlWriter != null) {
            try {
                xmlWriter.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }
}
于 2013-11-26T11:39:39.783 回答