Java 使用jaxb编组复杂类型xml元素
我在使用JAXB编组复杂类型元素(在它的示例中包含元素列表:device,请参见下文)时遇到了多个名称空间。感谢您在获得下面提到的所需输出方面提供的任何帮助Java 使用jaxb编组复杂类型xml元素,java,xml,namespaces,jaxb,marshalling,Java,Xml,Namespaces,Jaxb,Marshalling,我在使用JAXB编组复杂类型元素(在它的示例中包含元素列表: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:hel
<?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>
http://stackoverflow.com
这里,设备是扩展模式中定义的复杂类型元素。我和许多schema一起工作
但是,在设备复杂类型元素周围没有额外名称空间的情况下,所需的输出如下:
<?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>
http://stackoverflow.com
设备架构:
<?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);
}
final JAXBElement uri=objectFactory.createUri(uri);
元素elt=XmlMarshaller.getdoElement(uri,String.class);
最终设备设备=objectFactory.createDevice();
如果(elt!=null){
device.getAnies().add(elt);
}
elt=XmlMarshaller.getdoElement(设备,设备.class);
Request.getAnies().add(elt);
元素getDomeElement(最终对象,最终类clazz)抛出JAXBEException{
final-JAXBContext-JAXBContext=JAXBContext.newInstance(clazz);
final Marshaller jaxbMarshaller=jaxbContext.createMarshaller();
最终DOMResult res=新的DOMResult();
jaxbMarshaller.marshall(object,res);
最终元素elt=((文档)res.getNode()).getDocumentElement();
返回(elt);
}