簡體   English   中英

是否可以強制JAXB將XML標記中的非法字符編組?

[英]Is it possible to force JAXB to marshall illegal characters in an XML tag?

我有一個充滿對象的數據庫以及用戶定義的屬性。 例如:

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);
    }
}

我為此特定對象構建了一個XmlAdapter,然后:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
document.setStrictErrorChecking(false); // <--- This one. This accomplished it.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM