使用 JAXB 解析包含 <g:id> 等元素的 XML 文档

Parse XML document with elements like <g:id> using JAXB

<?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
  <channel>
    <title>SSS Product Feed</title>
    <link>https://en-ae.sssports.com/</link>
    <description><![CDATA[The largest sports ]]></description>
    <item>
      <g:id>NIKE315122-001</g:id>
      <g:title><![CDATA[Nike Air Force 1 Low 07 Shoe]]></g:title> 
      <g:sport>Lifestyle</g:sport>
    </item>
    <item>
      <g:id>NIKE315122-002</g:id>
      <g:title><![CDATA[Nike Air Force 1 Low 07 Shoe]]></g:title> 
      <g:sport>Lifestyle</g:sport>
    </item>
  </channel>
</rss>

这是我要阅读和解析的示例 xml 文件....

我有java class这样的....

 @XmlRootElement
 @XmlAccessorType(XmlAccessType.FIELD)
 public class Rss {


     @XmlElement(name="channel")
     private Channel channel;


     public Channel getChannel() {
         return channel;
     }

     public void setChannel(Channel channel) {
         this.channel = channel;
     }

}

另一个class是

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="item")
public class Item {

     @XmlElement(name="g:id")
     private String id;


     public String getId() {
         return id;
     }
     public void setId(String id) {
         this.id = id;
     }

最后一项 class 是

public class Channel {


    private List<Item> itemList;

    @XmlElement(name="item")
    public List<Item> getItemList() {
        return itemList;
    }

    public void setItemList(List<Item> itemList) {
        this.itemList = itemList;
    }
}

这就是我想要做的..请帮助我做错了什么,因为我从 xml returns 中提取的所有值都是 null.....

你的 RssChannel class 我觉得还不错。 问题出在您的 Item class,尤其是其带有名称空间的元素中。

要为 <g:id> 元素建模,您不得使用 @XmlElement(name = "g:id")。 相反,您需要使用 @XmlElement(name = "id", namespace = "http://base.google.com/ns/1.0")。 这对应于 XML 文件中给出的命名空间定义 xmlns:g="http://base.google.com/ns/1.0"

顺便说一句:在 Item class 上不需要 @XmlRootElement。 您仅在 Rss class 上需要它,因为 <rss> 是 XML 根元素。

完整的 Item class 看起来像这样:

@XmlAccessorType(XmlAccessType.FIELD)
public class Item {

    @XmlElement(name = "id", namespace = "http://base.google.com/ns/1.0")
    private String id;

    @XmlElement(name = "title", namespace = "http://base.google.com/ns/1.0")
    private String title;

    @XmlElement(name = "sport", namespace = "http://base.google.com/ns/1.0")
    private String sport;

    // public getters and setters (omitted here for brevity)
} 

您可以在此处找到更多背景信息: