繁体   English   中英

如何使用 JAXB 将 xmlns:xs 和 xmlns:xsi 移动到根元素?

[英]How to move xmlns:xs and xmlns:xsi to Root Element with JAXB?

我需要从 XSD 生成的 Java 类生成 XML 文件。

这些 Java 类中的一些字段作为Object而不是任何具体类型,因此保证生成的 XML 文件中有xsi:type属性,这很好。

xsi:type是,除了xsi:type ,还添加了完整的命名空间定义( xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ),并使 XML 非常不可读。

总而言之,这是我现在生成的内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns:RootTag xmlns:ns="https://example.com">
    <ns:SomeObjectField xsi:type="xs:boolean" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">true</ns:SomeObjectField>
    <ns:SomeOtherObjectField xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Some other value</ns:SomePtherObjectField>
</ns:RootTag>

这就是我想要生成的:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns:RootTag xmlns:ns="https://example.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ns:SomeObjectField xsi:type="xs:boolean">true</ns:SomeObjectField>
    <ns:SomeOtherObjectField xsi:type="xs:string">Some other value</ns:SomePtherObjectField>
</ns:RootTag>

我遇到过同样的问题。 假设您使用JAXBContext编组器的解决方案,您可以为您的命名空间或模式位置属性设置一个属性。 就我而言,我需要一个 noSchemaLocation:

 jaxbMarshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "facturaComputarizadaEstandar.xsd");

您可能需要为您的特定情况设置不同的属性。

您可以在package-info.java显式声明 xsi :

@javax.xml.bind.annotation.XmlSchema(
        xmlns = {
            @javax.xml.bind.annotation.XmlNs(
                    prefix = "ns",
                    namespaceURI = "https://example.com"),
            @javax.xml.bind.annotation.XmlNs(
                    prefix = "xsi",
                    namespaceURI = javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI) },
        namespace = "https://example.com",
        elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.foo;
  • prefix = "ns": <ns:RootTag>
  • prefix = "": <RootTag>

JAXBContextImpl.xmlNsSet

NamespaceContextImpl.declareNsUri()

JAXBContextImpl.schemaLocation

在较旧的 jaxb 实现 2.1 中, @XmlNs仅在生成架构文件时使用,作为解决方法,您可以添加:

@XmlSeeAlso(DummyTypeWithinXsi.class)
public class RootTag ...
...
@XmlRootElement(namespace = javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI)
public class DummyTypeWithinXsi {
}

_

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM