想象以下情况:我们从一些外部工具收到一个 xml 文件。最近在这个 xml 中,节点名称或它们的 richcontent 标签中可能有一些转义字符,如以下示例(简单):
<map>
<node TEXT="Project">
<node TEXT="ää">
<richcontent TYPE="NOTE"><html>
<head>
</head>
<body>
<p>
I am a Note for Node ää!
</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/