java - JAXB @XmlSchema 位置被忽略

标签 java xml groovy jaxb

我正在尝试使用 JAXB 生成 sitemap.xml,并且位置属性被忽略(我想在根元素上生成 xsi:schemaLocation 属性)。

我想生成一个 xml,如下所示:

<?xml version="1.0" encoding="UTF-8" ?>
<ns3:urlset 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ns3="http://www.sitemaps.org/schemas/sitemap/0.9"
    xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    <urls>
        <loc>http://domain.com</loc>
    </urls>
    <urls>
        <loc>http://domain.com/test</loc>
    </urls>
</ns3:urlset>

我还看到过其他问题: @xmlSchema annotation use with jaxbHow to generate the correct sitemap namespace using JAXB and Spring @ResponseBody in controller?

但是这些都不能解决我在使用注释时遇到的问题。

我有以下包信息:

@javax.xml.bind.annotation.XmlSchema(
    namespace = "http://www.sitemaps.org/schemas/sitemap/0.9",
    xmlns = @javax.xml.bind.annotation.XmlNs( prefix = "xsi", namespaceURI="http://www.w3.org/2001/XMLSchema-instance" ),
    location = "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED
)
package com.domain.site.sitemap

但是,我的单元测试:

@Test public void createXmlObject(){
    List urls = [ "test1", "test2", "test3" ]
    Sitemap map = new Sitemap( urls )
    JAXBContext jaxbContext = JAXBContext.newInstance( Sitemap )
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller()
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true)
    jaxbMarshaller.marshal(map, System.out)
}

生成根元素如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns3:urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="http://www.sitemaps.org/schemas/sitemap/0.9">

如果我更新测试以使用 jaxbMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "location..") 显式设置位置然后它将被填充 - 但我想了解为什么它不能与注释一起使用。

最佳答案

根据specification :

Note to implementor [...]

However, the schema generator is allowed to use a different value in the schemaLocation attribute (including not generating such attribute), for example so that the user can specify a local copy of the resource through the command line interface.

因此,是否生成位置取决于实现提供者。

关于java - JAXB @XmlSchema 位置被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29217397/

相关文章:

java - 使用 HashSet 相对于 HashMap 的优点

java - 在 Java 中执行方法时暂停执行 x 秒

java - Allure 框架 : TestNG adapter generates duplicate XML files

java - 以编程方式创建的 View 显示不正确 (android)

sql-server - SQL Server 2008/2012 不解析 XML Soap

java - 如何在非常大的文件中搜索字符串及其上方和下方文本的出现

java - 想要为类(dao)中的字段创建 View 绑定(bind)器。该字段将 json 作为文本

c# - 比较 XML 文件是否相等的最佳方法是什么?

java - Groovy 按更多标准分组

json - 复杂对象和集合的 Groovy/Grails JSON 转换