xml-serialization – 可以自定义JAXB编组到String时使用的命名
例如,我有一个简单的模式导入另一个模式。第二个模式(urn:just:attributes,just-attributes.xsd)只是定义一个属性组。
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/MySchema" xmlns:tns="http://www.example.org/MySchema" elementFormDefault="qualified" xmlns:ja="urn:just:attributes"> <import schemaLocation="just-attributes.xsd" namespace="urn:just:attributes"/> <element name="MyElement"> <complexType> <attributeGroup ref="ja:AttributeGroup"/> </complexType> </element> </schema> 我正在使用Metro xjc Ant任务来生成此模式的类。我正在遇到的问题是我正在进行互动的第三方应用程序对命名空间是特别的。这种情况我需要一个String值,所以我必须序列化它。我使用样板代码。 private static <T> String marshal(T object) throws JAXBException{ OutputStream outputStream = new ByteArrayOutputStream(); JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(object,outputStream); return outputStream.toString(); } 这给了我一些东西 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:MyElement xmlns:ns1="urn:just:attributes" xmlns:ns2="http://www.example.org/MySchema" ns1:attrib1="1234" ns1:attrib2="5678"/> 我的问题是这个第三方期望像xmlns这样的东西:thirdpartyns =“urn:just:attributes”,也就是说,它们是基于给命名空间的名称进行解析的。它的软件工作必须是“thirdpartyns”。 有没有人知道这个方法,没有做一个查找和替换在生成的字符串?自定义约束规则?
http://hwellmann.blogspot.com/2011/03/jaxb-marshalling-with-custom-namespace.html
这显示了如何做到这一点。 另一个: 如果链接也死亡的关键位: NamespacePrefixMapper类,位于com.sun.xml.bind.marshaller包中。抽象类有一种方法来实现: public abstract String getPreferredPrefix( String namespaceUri,String suggestion,boolean requirePrefix); 然后 Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(”com.sun.xml.bind.namespacePrefixMapper”,new MyNamespacePrefixMapper()); 如果您还使用javax.xml.xpath.XPath,您的NamespacePrefixMapper也可以实现javax.xml.namespace.NamespaceContext,将您的命名空间定制集中在一个类中。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |