我最近遇到了后续空间的问题。我将带有后续空格的文本附加到XML元素。 Xom的toXML方法运行正常但是使用Serializer编写带有ByteArrayOutputStream的字符缩小了空格。
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>
随后的空间正缩小为单一空间。我找不到原因
NOT:我看到Xom Serializer正在删除这些空格,因为我使用了indent和setMaxLength。是否有一个串行器没有触及文本并只是缩进?
答案 0 :(得分: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();
}
}
}
}