2
我可以使用JAXB編組我的站點地圖,但我無法解開它!任何幫助將非常感激。無法使用@XmlAttribute解組
我得到以下異常:
javax.xml.bind.UnmarshalException:意外的元素 (URI: 「http://www.sitemaps.org/schemas/sitemap/0.9」,地方: 「網址設定」)。 預期元件< {}的URL>,< {} urlset>結束
網站地圖網址設定:
@XmlRootElement(name = "urlset")
public class XMLURLSet
{
List<XMLURL> urls;
final String xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
@XmlAttribute(name = "xmlns")
public String getXmlns() {
return xmlns;
}
public void setXmlns(String xmlns) {
// nop
}
@XmlElement(name = "url")
public List<XMLURL> getUrls(){
return urls;
}
public void setUrls(List<XMLURL> urls) {
this.urls = urls;
}
網站地圖的URL:
@XmlRootElement(name = "urls")
public class XMLURL {
String loc;
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
輸出XML(這是正確的):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com</loc>
</url>
</urlset>
的JUnit編組代碼,工程
JAXBContext context = JAXBContext.newInstance(XMLURLSet.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
StringWriter sw = new StringWriter();
marshaller.marshal(urlSet, sw);
String xml = sw.toString();
解組即不工作(當從上方續」):
JAXBContext ctx = JAXBContext.newInstance(XMLURLSet.class);
Unmarshaller umsler = ctx.createUnmarshaller();
XMLURLSet xmlUrlSet = (XMLURLSet) umsler.unmarshal(new StreamSource(new StringReader(xml)));
最後一行生成異常:
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.sitemaps.org/schemas/sitemap/0.9", local:"urlset"). Expected elements are <{}urls>,<{}urlset>
很好完成。非常感謝,Blaise! – Pomario