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 に答える