当Object中包含XML时,将对象编组为XML(JAXB)

时间:2016-11-16 20:52:28

标签: java xml jaxb marshalling

我有一个简单的对象,我正试图编组成XML:

@XmlRootElement(name = "MyObject")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {

  @XmlElement(name = "ResultsAsString")
  private String resultsAsString;

  @XmlElement(name = "ResultsAsXml")
  private String resultsAsXml;
}

在第二个字段中,我传入了一些xml。但是,当我尝试使用JAXB封送对象时:

JAXBContext jaxbContext = JAXBContext.newInstance(MyObject.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

第二个字段中的xml出现乱码。所有“<”标签替换为“& lt”,引号替换为“& quot”但所有“>”标签保持不变。有没有理由为什么JAXB编码部分XML但留下“>”字符未编码?这在我的代码中很晚就破坏了功能。提前谢谢!

1 个答案:

答案 0 :(得分:0)

JAX-B不知道您的属性<包含有效的XML,因此它将其作为纯文本处理。

必须转义&&amp;才能创建有效的XML,请参阅Extensible Markup Language (XML) 1.1 (Second Edition)

  

&符号(&amp;)和左尖括号(&lt;)不得以其文字形式出现,除非用作标记分隔符,或用于注释,处理指令或CDATA部分。如果在其他地方需要它们,则必须分别使用数字字符引用或字符串“&lt;”和“&gt;”进行转义。右尖括号(&gt;)可以使用字符串“&gt;”来表示,并且为了兼容性,当它出现在字符串中时,必须使用“]]>”或字符引用进行转义“ Dim Doc As Document Dim sTempFilePath As String sTempFilePath = ("C:\temp\test.doc") 'the next line copies the active document Application.Documents.Add ActiveDocument.FullName ActiveDocument.SaveAs FileName:="C:\temp\test.doc" ActiveDocument.Close Kill sTempFilePath “在内容中,当该字符串未标记CDATA部分的结尾时。

相关问题