我需要从 XSD 生成的 Java 类生成 XML 文件。
这些 Java 类中的某些字段作为 Object
而不是任何具体类型,因此在生成的 XML 文件中保证有 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");
您可能需要为您的具体情况设置不同的属性。
关于java - 如何移动 xmlns :xs and xmlns:xsi to Root Element with JAXB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52896340/