java - 使用 JAXB 解码 XML 而无需转义字符

标签 java xml escaping unmarshalling

想象以下情况:我们从一些外部工具收到一个 xml 文件。最近在这个 xml 中,节点名称或它们的 richcontent 标签中可能有一些转义字符,如以下示例(简单):

<map>
<node TEXT="Project">
<node TEXT="&#xe4;&#xe4;">
<richcontent TYPE="NOTE"><html>
  <head>

  </head>
  <body>
    <p>
      I am a Note for Node &#228;&#228;!
    </p>
  </body>
</html>
</richcontent>
</node>
</node>
</map>

在使用 JAXB 解码文件后,那些转义字符将被取消转义。不幸的是,我需要他们保持原样,意思是逃脱。有什么方法可以避免在解码时对这些字符进行转义?

在研究过程中,我发现了很多关于编码 xml 文件的问题,但这些问题都没有帮助我:

是否有可能使用 JAXB 实现这个目标,或者我们是否必须考虑更改为不同的 xml 读取器 API?

先谢谢你, 伊梅内

最佳答案

您只需将 &# 替换为 &# 因此调用

unmarshaller.unmarshal(new AmpersandingStream(new FileInputStream(...)));

import java.io.IOException;
import java.io.InputStream;

/**
* Replaces numerical entities with their notation as text.
*/
public class AmpersandingStream extends InputStream {

    private InputStream in;
    private boolean justReadAmpersand;
    private String lookAhead = "";

    public AmpersandingStream(InputStream in) {
        this.in = in;
    }

    @Override
    public int read() throws IOException {
        if (!lookAhead.isEmpty()) {
            int c = lookAhead.codePointAt(0);
            lookAhead = lookAhead.substring(Character.charCount(c));
            return c;
        }
        int c = in.read();
        if (c == (int)'#' && justReadAmpersand) {
            c = (int)'a';
            lookAhead = "mp;#";
        }
        justReadAmpersand = c == (int)'&';
        return c;
    }

    @Override
    public int available() throws IOException {
        return in.available();
    }

    @Override
    public void close() throws IOException {
        in.close();
    }

    @Override
    public synchronized void mark(int readlimit) {
        in.mark(readlimit);
    }

    @Override
    public boolean markSupported() {
        return in.markSupported();
    }

    @Override
    public int read(byte[] b) throws IOException {
        return in.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return in.read(b, off, len);
    }

    @Override
    public synchronized void reset() throws IOException {
        in.reset();
    }

    @Override
    public long skip(long n) throws IOException {
        return in.skip(n);
    }

}

关于java - 使用 JAXB 解码 XML 而无需转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9296476/

相关文章:

java - 使用 Hibernate 搜索进行搜索

c++ - libxml2 XPATH - 从 XML 中选择数据子集

java - 我如何在 Java 中转义 URL(文档不清楚)?

javascript - 如何使用 javascript 使自定义数据属性值成为数字

javascript - 如何使用 javascript 在正则表达式替换中表示大括号

java - 在maven构建期间远程部署java jar

java - Jasper 报告中的评估异常

java - 使用正则表达式获得最佳小组比赛

sql-server - 如何从 XSD 架构构建数据库并导入 XML 数据

xml - XML 与 RDMS 相比的优点/缺点