使用jaxb编组复杂类型的xml元素

时间:2014-11-14 19:46:48

标签: java xml namespaces jaxb marshalling

我正在运行多个名称空间,同时使用JAXB编组复杂类型的Element(包含Element的列表示例:device见下文)。感谢获得所需输出的任何帮助,如下所述。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Request xmlns="urn:ietf:params:xml:ns:geopriv:held"        
xmlns:ns2="urn:ietf:params:xml:ns:geopriv:held:id" 
xmlns:ns3="urn:ietf:params:xml:ns:geopriv:held:vendor" responseTime="10">    
<ns2:device xmlns="urn:ietf:params:xml:ns:geopriv:held:id"
            xmlns:ns2="urn:ietf:params:xml:ns:geopriv:held">
    <uri>http://stackoverflow.com</uri>
</ns2:device>

此处device是扩展架构中定义的复杂类型元素。我正在使用许多架构。

但是没有设备复杂类型元素周围的额外命名空间的所需输出是这样的:

<?xml version="1.0" encoding="utf-8"?>
<Request xmlns="urn:ietf:params:xml:ns:geopriv:held" responseTime="10"> 
<device xmlns="urn:ietf:params:xml:ns:geopriv:held:id">
    <uri>http://stackoverflow.com</uri>
 </device>
 </Request>

设备架构:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="urn:ietf:params:xml:ns:geopriv:held:id"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:id="urn:ietf:params:xml:ns:geopriv:held:id"
elementFormDefault="qualified" attributeFormDefault="unqualified">

<xs:element name="device" type="id:deviceIdentity" />
<xs:complexType name="deviceIdentity">
    <xs:sequence>
        <xs:any xmlns:id="urn:ietf:params:xml:ns:geopriv:held:id"
                processContents="strict" minOccurs="0"
            maxOccurs="unbounded" />
    </xs:sequence>
</xs:complexType>

编组代码:

        final JAXBElement<String> uri = objectFactory.createUri(uri);

        Element elt = XmlMarshaller.getDomElement(uri, String.class);
        final Device device = objectFactory.createDevice();
        if (elt != null) {
            device.getAnies().add(elt);
        }

        elt = XmlMarshaller.getDomElement(device, Device.class);
        Request.getAnies().add(elt);


Element getDomElement(final Object object, final Class<?> clazz) throws JAXBException {

    final JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
    final Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    final DOMResult res = new DOMResult();
    jaxbMarshaller.marshal(object, res);
    final Element elt = ((Document) res.getNode()).getDocumentElement();

    return (elt);
}

0 个答案:

没有答案