如何在JAXB

时间:2017-03-28 09:51:39

标签: java xml jaxb

我的测试xml内容

    <p id="033" num="03">geopotent change&#x2 high.</p>

我运行Jaxb Unmarshalling,但我得到了异常

    09:58:43.748 ERROR [main][net.ServiceImpl] Parsing Error: 
    javax.xml.bind.UnmarshalException- with linked exception:    
    [javax.xml.stream.XMLStreamException: ParseError at [row,col]:
    [161,306]Message: String "&#]

我的Jaxb unmarshal来源是

    JAXBContext jaxbContext = JAXBContext.newInstance(CnDocument.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    document = (CnDocument) jaxbUnmarshaller.unmarshal(xmlFile);

我怎样才能逃脱这些角色? (安培;#X2)

3 个答案:

答案 0 :(得分:0)

您收到JAXB解析错误,因为您的XML内容格式不正确。 它应该是&#x2;(带分号),而不是&#x2

答案 1 :(得分:0)

<p id="033" num="03">geopotent change&#x2 high.</p>不是有效的XML。要么&#34;逃避&#34;使用&amp;的&符号或通过添加分号来完成字符参考:&#x2;

答案 2 :(得分:0)

这是你可以做的一种方式:

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;

public class XmlCharacterHandler implements CharacterEscapeHandler {

    public void escape(char[] buf, int start, int len, boolean isAttValue,
            Writer out) throws IOException {
        StringWriter buffer = new StringWriter();

        for (int i = start; i < start + len; i++) {
            buffer.write(buf[i]);
        }

        String st = buffer.toString();

        if (!st.contains("CDATA")) {
            st = buffer.toString().replace("&", "&amp;").replace("<", "&lt;")
                .replace(">", "&gt;").replace("'", "&apos;")
                .replace("\"", "&quot;");

        }
        out.write(st);
        System.out.println(st);
    }

}

编组时:

marshaller.setProperty(CharacterEscapeHandler.class.getName(),
                new XmlCharacterHandler());