I am trying to create a Sitemap index file with JAXB. Following the requirements for creating the sitemap, I have to add the namespace attribute in the root element:
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
I would like to have a simple way to sort this out. Since this seems to be a standard procedure I would like to not do a complex workaround or add more dependencies to my project in order to solve this issue
The current output is the following:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:sitemapindex xmlns:ns2="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>https://www.example.com/sitemap-1.xml</loc>
<lastmod>2017-05-01T15:41:17.561+01:00</lastmod>
</sitemap>
</ns2:sitemapindex>
My SitemapIndex
model is the following:
@XmlRootElement(name = "sitemapindex", namespace="http://www.sitemaps.org/schemas/sitemap/0.9")
@XmlAccessorType(XmlAccessType.FIELD)
public class SitemapIndex {
@XmlElement(name = "sitemap")
private List<Sitemap> sitemaps;
public void setSitemaps(List<Sitemap> sitemaps) {
this.sitemaps = sitemaps;
}
public List<Sitemap> getSitemaps() {
return sitemaps;
}
}
I have also tried to add the namespace field manually and it works for generating the file but I an exception is thrown when I try to read the file.
@XmlAttribute(name="xmlns")
private final String namespace ="http://www.sitemaps.org/schemas/sitemap/0.9";
You can use @XmlSchema
[1] package level annotation in order to set prefix. In your case, we just set empty prefix.
Simply create package-info.java
file in your package e.g. com.stackoverflow.jaxb
, with similar content.
package-info.java
@XmlSchema(namespace = "http://www.sitemaps.org/schemas/sitemap/0.9",
xmlns = {@XmlNs(prefix = "",
namespaceURI = "http://www.sitemaps.org/schemas/sitemap/0.9")},
elementFormDefault = XmlNsForm.QUALIFIED)
package com.stackoverflow.jaxb;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
Note, that you can remove namespace
attribute from @XmlRootElement
annotation.
[1] https://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/annotation/XmlSchema.html