如何在Java中使用Jaxb2Marshaller在最终XML中禁用xmlns targetNamespace

时间:2019-01-08 12:12:42

标签: xml spring xsd jaxb xml-namespaces

我有一个运行良好的XML文件编写器类,该类使用Jaxb2Marshaller用以下代码编写最终的XML文件:

final String XSD_FILE_NAME = myxsd.xsd
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setSchema(resourceLoader.getResource("classpath:xml/" + XSD_FILE_NAME));
marshaller.setContextPath("com.my.project.type");
marshaller.setMarshallerProperties(ImmutableMap.of(
        JAXB_FORMATTED_OUTPUT, Boolean.TRUE,
        JAXB_NO_NAMESPACE_SCHEMA_LOCATION, XSD_FILE_NAME
));
marshaller.afterPropertiesSet();

// this is the way to write into cache for validation:
JAXBElement<MyFile> myFileToMarshall = new ObjectFactory().createMyFile();
try {
    marshaller.marshal(myFileToMarshall, new SAXResult(new DefaultHandler()));
} catch (XmlMappingException xme) {
    throw new RuntimeException("Unable to create exact xml file, because the data is not valid!", xme);
}

try (FileOutputStream fileOutputStream = new FileOutputStream("C:/tmp/file.xml")) {
    marshaller.marshal(myFileToMarshall, new StreamResult(fileOutputStream));
} catch (IOException e) {
    throw new RuntimeException("Exact XML writing failed", e);
}

XSD的开头看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" attributeFormDefault="unqualified"
           targetNamespace="http://xmlns.myproject.com/v1"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:tns="http://xmlns.myproject.com/v1">

最终生成的文件的开头看起来像这样:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<eExact xmlns="http://xmlns.myproject.com/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="myxsd.xsd">

我想要的是什么

我想从最终文件中删除xmlns="http://xmlns.myproject.com/v1"部分,但能够使用XSD验证最终文件。

有可能吗?

0 个答案:

没有答案