gpt4 book ai didi

java - 使用 SAXParser 解析 xml 时出现意外行为

转载 作者:行者123 更新时间:2023-12-02 11:41:30 25 4
gpt4 key购买 nike

我只是读取 xml 并写回 xml:

<p>Il <b>1888</b> (MDCCCLXXXVIII in numeri romani) è un anno bisestile del XIX secolo.</p>

结果是:

<p>Il<b>1888</b> (MDCCCLXXXVIII in numeri romani) è un anno bisestile del XIX secolo.</p>

如你所见,我失去了一个空格。

有人可以解释一下为什么吗?或者我该如何防止这种情况发生?

我的代码:

 package parsing;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class TextCase {

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String text = "<p>Il <b>1888</b> (MDCCCLXXXVIII in numeri romani) è un anno bisestile del XIX secolo.</p>";
String newString = readSave(text);
System.out.println(newString);

}

public static String readSave(String text) throws Exception {


InputStream is = new ByteArrayInputStream((text).getBytes(StandardCharsets.UTF_8.name()));
SAXBuilder saxBuilder = new SAXBuilder();
Document document = saxBuilder.build(is);
Element classElement = document.getRootElement();

//processElement(classElement, months, monthIndex);

XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat().setOmitDeclaration(true));
String output = outputter.outputString(classElement);

return output;
}
}

最佳答案

您需要使用Format.getRawFormat()而不是Format.getCompactFormat()

Format.getCompactFormat()

<p>Il<b>1888</b>(MDCCCLXXXVIII in numeri romani) è un anno bisestile del XIX secolo.</p>

Format.getPrettyFormat()

<p>
Il
<b>1888</b>
(MDCCCLXXXVIII in numeri romani) è un anno bisestile del XIX secolo.
</p>

Format.getRawFormat()

<p>Il <b>1888</b> (MDCCCLXXXVIII in numeri romani) è un anno bisestile del XIX secolo.</p>

关于java - 使用 SAXParser 解析 xml 时出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48516980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com