【问题标题】:unexpected behaviour parsing xml with SAXParser使用 SAXParser 解析 xml 的意外行为
【发布时间】:2018-01-30 08:28:50
【问题描述】:

我只是在读取 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.getCompactFormat() 看起来可能是罪魁祸首。如果您提供 minimal reproducible example 并提及您正在使用 JDom... 会有所帮助
  • 我调整了问题,我在这个案例中添加了完整的最小代码。

标签: java parsing sax


【解决方案1】:

您需要使用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>

【讨论】:

    猜你喜欢
    • 2013-03-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2013-01-24
    • 2013-01-06
    • 2012-07-30
    相关资源
    最近更新 更多