【问题标题】:Multiple elements with the same name with SimpleXML and Java使用 SimpleXML 和 Java 具有相同名称的多个元素
【发布时间】:2011-10-26 22:29:49
【问题描述】:

我正在尝试使用 SimpleXML 来解析包含以下元素的 XML 文档(ItemLookupResponse 来自 Amazon Product Advertising API 的一本书):

<ItemAttributes>
  <Author>Shane Conder</Author>
  <Author>Lauren Darcey</Author>
  <Manufacturer>Pearson Educacion</Manufacturer>
  <ProductGroup>Book</ProductGroup>
  <Title>Android Wireless Application Development: Barnes & Noble Special Edition</Title>
</ItemAttributes>

我的问题是我不知道如何处理多个可能的Author 元素。

这是我现在拥有的对应 POJO(普通旧 Java 对象)的内容,请记住,它不处理多个 Authors 的情况:

@Element
public class ItemAttributes {
    @Element
    public String Author;

    @Element
    public String Manufacturer;

    @Element
    public String Title;
}

(我不关心ProductGroup,所以它不在课堂上——我只是将SimpleXML 的strict 模式设置为off 以允许这样做。)

我在the documentation 中找不到与这种情况相对应的示例。使用 ElementList(inline=true) 似乎是正确的,但我没有看到如何为 String 做这件事(与单独的 Author 类相反,我不需要也看不到它会如何甚至工作)。

这是一个类似的问题和答案,但对于 PHP:php - simpleXML how to access a specific element with the same name as others? 我不知道 Java 等效于接受的答案。

提前致谢。

【问题讨论】:

    标签: java android xml amazon simple-framework


    【解决方案1】:

    注意,这只是来自阅读文档(唯一的问题是它应该是 name="Author" 还是 entry="Author"):

    @Element
    public class ItemAttributes {
        @Element(inline=true, type=String.class, name="Author")
        public List<String> authors;
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多