Build sitemap.xml by Java Spring [duplicate]
Asked Answered
B

1

4

I'm building a sitemap.xml by Spring MVC

@XmlRootElement(name = "urlset")
public class XmlUrlSet{
@XmlElements(@XmlElement(name = "url", type = XmlUrl.class))
private List<XmlUrl> sitemap = new ArrayList<XmlUrl>();

public void addUrl(XmlUrl xmlUrl) {
    sitemap.add(xmlUrl);
}

public List<XmlUrl> getXmlUrls() {
    return sitemap;
}
}

And it renders like this:

<urlset>
    <url>
        ...
    </url>
    <url>
        ...
    </url>
</urlset>

I just want to know how to add namespace for xml and xml version like Google's sitemap example?

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.example.com/foo.html</loc> 
   </url>
</urlset>
Bretbretagne answered 30/7, 2015 at 3:18 Comment(1)
have a look at this #8403075Xochitlxp
C
5

I hope you might have found your solution. Still, this answer may be helpful to someone.

Replacing @XmlRootElement(name = "urlset") with @XmlRootElement(name = "urlset", namespace = "http://www.sitemaps.org/schemas/sitemap/0.9") would solve your problem.

Update

If you have tried above solution. You will get the result something like following.

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

Solve this problem by adding package-info.java file in your package where you have placed XmlUrlSet class with the following content.

@XmlSchema(
    namespace="http://www.something.com/something", 
    elementFormDefault=XmlNsForm.QUALIFIED)
package your.package;

import javax.xml.bind.annotation.*;

It should solve your problem.

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
    </url>
</urlset>
Cradle answered 20/4, 2017 at 10:37 Comment(4)
adding package-info.java can't remove the namespace ns2. Do you know why?Boehmenist
w3cgeek.com/… This link saved me. :)Boehmenist
@YeWin: the link is invalidHorotelic
Worked for me, but I had to change the Url in XMLSchema from http://www.something.com/something to http://www.sitemaps.org/schemas/sitemap/0.9Horotelic

© 2022 - 2024 — McMap. All rights reserved.