java - 使用jaxb将xml解析为java对象时接收错误

标签 java xml jaxb xsd

使用 xjc,我从以下 xml 生成了以下 java 类。

xjc 命令:

xjc -p sample sample.xsd

从sample.xml生成的xsd文件:

<xs:schema attributeFormDefault="unqualified" 
           elementFormDefault="qualified" 
           targetNamespace="http://rssnamespace.org/feedburner/ext/1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="origLink" type="xs:anyURI"/>
  <xs:element name="info">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute type="xs:string" name="uri"
                        use="optional"/>
          <xs:attribute type="xs:string" name="rel" 
                        use="optional"/>
          <xs:attribute type="xs:anyURI" name="href" 
                        use="optional"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

样本.xml:

<?xml version=\\\"1.0\" encoding=\\\"UTF-8\"\\?>
<?xml-stylesheet type="text/xsl" media="screen\" href=\"/~d/styles/rss2full.xsl\"?>
<?xml-stylesheet type="text/css" media="screen\" href=\"http://feeds.arsenal.com/~d/styles/itemcontent.css"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/\" xmlns:feedburner=\"http://rssnamespace.org/feedburner/ext/1.0" version=\"2.0\">
   <channel>
      <title><![CDATA[Arsenal FC News Feed]]></title>
      <link>http://feeds.arsenal.com/arsenal-news</link>
      <description><![CDATA[Arsenal FC News Headlines]]></description>
      <pubDate>Thu, 05 Dec 2013 16:05:34 +0000</pubDate>
      <managingEditor>website@arsenal.co.uk (Arsenal)</managingEditor>
      <copyright>Copyright(C) 2013 Arsenal Broadband Ltd</copyright>
      <generator>Arsenal</generator>
      <language>en-gb</language>
      <docs>http://blogs.law.harvard.edu/tech/rss</docs>
      <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.arsenal.com/arsenal-news" />
      <feedburner:info uri="arsenal-news" />
      <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" />
      <item>
         <title><![CDATA[Peter Hill-Wood honoured by the Club]]></title>
         <link>http://feeds.arsenal.com/~r/arsenal-news/~3/OZfGaLyOb9I/former-arsenal-chairman-honoured-by-club</link>
         <guid isPermaLink="false">http://www.arsenal.com/50466</guid>
         <description>Bust of former Arsenal chairman unveiled at Emirates Stadium in commemoration of his contribution to the Club&lt;img src="http://feeds.feedburner.com/~r/arsenal-news/~4/OZfGaLyOb9I" height="1" width="1"/&gt;</description>
         <pubDate>Thu, 05 Dec 2013 16:05:34 +0000</pubDate>
         <feedburner:origLink>http://www.arsenal.com/news/news-archive/former-arsenal-chairman-honoured-by-club</feedburner:origLink>
      </item>
   </channel>
</rss>

这是生成的java类:

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2013.12.05 at 10:15:01 PM GMT 
//


package rss;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;


/**
 * <p>Java class for anonymous complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType>
 *   &lt;simpleContent>
 *     &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string">
 *       &lt;attribute name="uri" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       &lt;attribute name="rel" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       &lt;attribute name="href" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *     &lt;/extension>
 *   &lt;/simpleContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "value"
})
@XmlRootElement(name = "info")
public class Info {

    @XmlValue
    protected String value;
    @XmlAttribute
    protected String uri;
    @XmlAttribute
    protected String rel;
    @XmlAttribute
    @XmlSchemaType(name = "anyURI")
    protected String href;

    /**
     * Gets the value of the value property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * Gets the value of the uri property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getUri() {
        return uri;
    }

    /**
     * Sets the value of the uri property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setUri(String value) {
        this.uri = value;
    }

    /**
     * Gets the value of the rel property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getRel() {
        return rel;
    }

    /**
     * Sets the value of the rel property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setRel(String value) {
        this.rel = value;
    }

    /**
     * Gets the value of the href property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getHref() {
        return href;
    }

    /**
     * Sets the value of the href property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setHref(String value) {
        this.href = value;
    }

}

我用来将 xml 文件转换为 pojo 的 java 代码:

public class JaxBConvert {
    public static void main(String[] args) {

         try {

            File file = new File("C:\\sample.xml");

            JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Info info = (Info) jaxbUnmarshaller.unmarshal(file);
            System.out.println(info);

          } catch (JAXBException e) {
            e.printStackTrace();
          }

    }
}

但我收到此错误:

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"rss"). Expected elements are <{http://rssnamespace.org/feedburner/ext/1.0}info>,<{http://rssnamespace.org/feedburner/ext/1.0}origLink>
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:647)

我的java对象正确吗?

更新:我使用了 http://www.freeformatter.com/xsd-generator.html生成 XSD 架构:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://rssnamespace.org/feedburner/ext/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="origLink" type="xs:anyURI"/>
  <xs:element name="info">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute type="xs:string" name="uri" use="optional"/>
          <xs:attribute type="xs:string" name="rel" use="optional"/>
          <xs:attribute type="xs:anyURI" name="href" use="optional"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

来自此 XML:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?>
<?xml-stylesheet type="text/css" media="screen" href="http://feeds.arsenal.com/~d/styles/itemcontent.css"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
   <channel>
      <title><![CDATA[Arsenal FC News Feed]]></title>
      <link>http://feeds.arsenal.com/arsenal-news</link>
      <description><![CDATA[Arsenal FC News Headlines]]></description>
      <pubDate>Thu, 05 Dec 2013 16:05:34 +0000</pubDate>
      <managingEditor>website@arsenal.co.uk (Arsenal)</managingEditor>
      <copyright>Copyright(C) 2013 Arsenal Broadband Ltd</copyright>
      <generator>Arsenal</generator>
      <language>en-gb</language>
      <docs>http://blogs.law.harvard.edu/tech/rss</docs>
      <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.arsenal.com/arsenal-news" />
      <feedburner:info uri="arsenal-news" />
      <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" />
      <item>
         <title><![CDATA[Peter Hill-Wood honoured by the Club]]></title>
         <link>http://feeds.arsenal.com/~r/arsenal-news/~3/OZfGaLyOb9I/former-arsenal-chairman-honoured-by-club</link>
         <guid isPermaLink="false">http://www.arsenal.com/50466</guid>
         <description>Bust of former Arsenal chairman unveiled at Emirates Stadium in commemoration of his contribution to the Club&lt;img src="http://feeds.feedburner.com/~r/arsenal-news/~4/OZfGaLyOb9I" height="1" width="1"/&gt;</description>
         <pubDate>Thu, 05 Dec 2013 16:05:34 +0000</pubDate>
         <feedburner:origLink>http://www.arsenal.com/news/news-archive/former-arsenal-chairman-honoured-by-club</feedburner:origLink>
      </item>
   </channel>
</rss>

更新2:

阅读这篇博文:http://vbvyas.wordpress.com/2011/10/11/java-parsing-rss-xml-using-xpath/ 使用 xpath 进行解析似乎要简单得多:

import org.w3c.dom.*;
import org.xml.sax.InputSource;
import javax.xml.xpath.*;
import javax.xml.parsers.*;

public class XmlParser {
 public static void main(String[] args) {
 try {
  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  domFactory.setNamespaceAware(true);
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  URL url = new URL("http://www.somesite.com/index.php?format=feed&type=rss");
  InputStream inputStream = url.openStream();
  Reader reader = new InputStreamReader(inputStream, "UTF-8");
  InputSource inputSource = new InputSource(reader);
  Document doc = builder.parse(inputSource);
  XPath xpath = XPathFactory.newInstance().newXPath();
  XPathExpression expr = xpath.compile("//rss/channel/item/title/text()");
  NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
   for (int i = 0; i < nodes.getLength(); i++)
   {
    String title = nodes.item(i).getNodeValue();
    System.out.println(title);
   }
  }
  catch (Exception exception) {
   exception.printStackTrace();
  }
 }
}

最佳答案

根据您生成模型所依据的 XML 架构,JAXB 将期望文档如下所示:

<info 
    xmlns="http://rssnamespace.org/feedburner/ext/1.0"
    url="A"
    rel="B"
    fref="http://www.example.com"/>

或者

<origLink>http://www.example.com</origLink>

如果您想要解码不符合此 XML 架构的 XML 文档(例如您的 sample.xml),那么您将需要创建另一个映射到该 XML 文档结构的模型。

关于java - 使用jaxb将xml解析为java对象时接收错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20412877/

相关文章:

java - 使用 xmldsig 签名的 JAXB 编码

java - Java中不同类型的类使用相同的方法

java - 在 redis 中保存 Set<String> 的 Value 的序列化程序

python - 通过lxml python更改xml中的属性值

java - 如何在 OSGi 包中查找带注释的类

java - Jackson 中的 @XmlPath 模拟是什么?

java - 如何在JAVA中读取一个大的XML文件并根据标签将其分割成小的XML文件?

java - 如何在最后一个 JFrame 处理期间在 Swing 中显示 "Application Closing.."消息?

java - Eclipse 声称 Commons-Codec 方法不存在

java - 多部分 Http 请求