0

我有一个充满对象的数据库,以及用户定义的属性。例如:

class Media {
  String name;
  String duration;
  Map<String,String> custom_tags;
}


Media:
  Name: day_at_the_beach.mp4
  Length: 4:22
  Custom Tags:
    Videographer: Charles
    Owner ID #: 17a

我们的用户可以提出自己的自定义属性来附加到媒体,并相应地填写值。但是,当我尝试将对象编组为 XML 时,我遇到了问题:

<media>
  <name>day_at_the_beach.mp4</name>
  <length>4:22</length>
  <custom_tags>
    <Videographer>Charles</videographer>
    <Owner_ID_#>17a</Owner_ID_#>
  </custom_tags>
</media>

Owner_ID_#是 XML 中的非法标记名称,因为它包含一个#所以 JAXB 抛出一个org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.

我知道解决此问题的首选正确方法是将 xml 重新格式化为以下内容:

<custom_tags>
  <custom_tag>
    <name>Owner ID #</name>
    <value>17z</value>
  </custom_tag>
</custom_tags>

但是,我需要返回以前的无效 XML,以维护以前的、不那么挑剔的代码实现的遗留行为。有什么方法可以告诉 JAXB 不要担心非法的 XML 字符,或者我会在编码之前/之后进行字符串替换吗?我目前的实现很简单:

public static <T> String toXml(Object o, Class<T> z) {
    try {
        StringWriter sw = new StringWriter();
        JAXBContext context = JAXBContext.newInstance(z);
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(o, sw);
        return sw.toString();
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
}
4

1 回答 1

0

我为这个特定对象构建了一个 XmlAdapter,然后:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
document.setStrictErrorChecking(false); // <--- This one. This accomplished it.
于 2012-07-27T21:34:42.447 回答