How to generate the correct sitemap namespace usin

2020-02-14 02:36发布

问题:

Everything is working fine with the exception that I cannot create the namespace correctly. Any help is much appreciated!

My controller:

@Controller
@RequestMapping("/sitemap")
public class SitemapController
{
    public @ResponseBody XMLURLSet getSitemap(){
       XMLURLSet urlSet = new XMLURLSet();
       //populate urlList
       urlSet.setUrl(urlList);
       return urlSet;
    }
}

My urlset:

@XmlRootElement(name = "url")
public class XMLURL {
   String loc;
   @XmlElement(name = "loc")
   public String getLoc(){
      return loc;
   }
   public void setLoc(String loc){
   this.loc = loc;
}

}

My url element:

   @XmlRootElement(name = "urlset", namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")
    public class XMLURLSet{
       List<XMLURL> url;
       public List<XMLURL> getUrl(){
          return url;
       }
       public void setUrl(List<XMLURL> url){
       this.url = url;
    }

}

What I expected to be generated:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
</url>

What got generated:

<ns2:urlset xmlns:ns2="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
</url>
</ns2:urlset>
</urlset> 

Thanks!

回答1:

You can leverage the @XmlSchema annotation to specify elementFormDefault is qualified. This should help with your use case.

@XmlSchema(
    namespace = "http://www.sitemaps.org/schemas/sitemap/0.9",
    elementFormDefault = XmlNsForm.QUALIFIED)
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

For More Information

  • http://blog.bdoughan.com/2010/08/jaxb-namespaces.html