相关疑难解决方法(0)

是否可以自定义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>
Run Code Online (Sandbox Code Playgroud)

我正在使用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();
}
Run Code Online (Sandbox Code Playgroud)

这给了我一些东西

<?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"/>
Run Code Online (Sandbox Code Playgroud)

xmlns:thirdpartyns="urn:just:attributes"遇到的问题是这个第三方需要类似的东西,也就是说,它们是根据命名空间的名称进行解析.它已经是"thirdpartyns"为他们的软件工作.

有没有人知道如何解决这个问题,而不是在结果字符串中进行查找和替换?也许是自定义绑定规则?

java-metro-framework jaxb xml-serialization jaxb2

25
推荐指数
3
解决办法
5万
查看次数