无法使用@XmlAttribute解组

时间:2011-12-07 15:52:14

标签: jaxb marshalling unmarshalling

我可以用JAXB编组我的站点地图,但我不能解组它!任何帮助将不胜感激。

我得到以下异常:

  

javax.xml.bind.UnmarshalException:意外元素   (uri:“http://www.sitemaps.org/schemas/sitemap/0.9”,local:“urlset”)。   预期元素为< {} urls>,< {} urlset>

Sitemap 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;
   }

站点地图网址:

@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>

1 个答案:

答案 0 :(得分:1)

问题在于您尝试命名空间限定文档的方式。您需要在与域类相同的包中添加一个名为package-info的类,并带有以下条目:

<强>包信息

@XmlSchema(
    namespace = "http://www.sitemaps.org/schemas/sitemap/0.9",
    elementFormDefault = XmlNsForm.QUALIFIED)
package your.package.name;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

了解更多信息