How to generate the correct sitemap namespace using JAXB and Spring @ResponseBody in controller?
Asked Answered
A

1

7

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!

Ation answered 6/12, 2011 at 15:40 Comment(0)
B
6

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

Brain answered 6/12, 2011 at 16:11 Comment(4)
Where can I find the content of the file package-info?Ation
package-info is actually a class so you will have a package-info.java in the same package as your domain classes with content similar to what is given in my answer.Brain
it works. on the same thread, how would you add the encoding of the XML to generate <?xml version="1.0" encoding="UTF-8"?>. I have seen how to do it manipulating the Marshler, though, my code does not allow me to do thatAtion
@Pomario - By default JAXB will generate a head (the following may help: blog.bdoughan.com/2011/08/…). In your use case JAXB may be marshalling into a stream started by spring so you may need to configure something at that level.Brain

© 2022 - 2024 — McMap. All rights reserved.