我想从 XML 创建一些对象,但是当我尝试时出现此错误:
[26/07/12 16:20:03:763 CEST] ERROR sitemap.SitemapXMLServlet:
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.sitemaps.org/schemas/sitemap/0.9", local:"urlset"). Expected elements are <{}url>
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.sitemaps.org/schemas/sitemap/0.9", local:"urlset"). Expected elements are <{}url>
我找不到问题,也不明白为什么会出错。这是我尝试过的:
XML 文件
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://LINK/shop/hoofdcategorie</loc>
<lastmod>2012-07-26</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>
http://LINK/shop/hoofdcategorie/subcategorie
</loc>
<lastmod>2012-07-26</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
</urlset>
将 XML 解组为对象的方法
public void getXML() {
final JAXBContext context = JAXBContext.newInstance(SitemapXML.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
String xml = URLReader.readUrlHttpClient("http://LINK/shop/sitemap.xml");
final UrlSet urlSet = (UrlSet) unmarshaller.unmarshal(new StreamSource(new StringReader(xml)));
}
UrlSet 类
@XmlRootElement(name = "urlset")
public class UrlSet {
@XmlAttribute
String xmlns;
@XmlElement(name = "url")
ArrayList<SitemapXML> sitemaps;
public ArrayList<SitemapXML> getSitemaps() {
return sitemaps;
}
public void setSitemaps(ArrayList<SitemapXML> sitemaps) {
this.sitemaps = sitemaps;
}
@XmlAttribute
public String getXmlns() {
return xmlns;
}
public void setXmlns(String xmlns) {
this.xmlns = xmlns;
}
}
我映射到 url 的 SitemapXML 类
@XmlRootElement(name = "url")
public class SitemapXML {
String loc;
Date lastmod;
String changefreq;
Double priority;
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public Date getLastmod() {
return lastmod;
}
public void setLastmod(Date lastmod) {
this.lastmod = lastmod;
}
public String getChangefreq() {
return changefreq;
}
public void setChangefreq(String changefreq) {
this.changefreq = changefreq;
}
public Double getPriority() {
return priority;
}
public void setPriority(Double priority) {
this.priority = priority;
}
}