使用 SimpleXML 和 Java 实现多个同名元素
我正在尝试使用 SimpleXML 解析 XML 文档(亚马逊产品广告 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 对象),请记住它不处理多个 Author
的情况:(
@Element
public class ItemAttributes {
@Element
public String Author;
@Element
public String Manufacturer;
@Element
public String Title;
}
我不关心 ProductGroup
,所以它不在类中 - 我只是将 SimpleXML 的 strict
模式设置为 off
以允许这种情况。)
我找不到示例在 与此类案例对应的文档。将 ElementList
与 (inline=true)
一起使用似乎是正确的,但我不知道如何对 String 执行此操作(与单独的 Author 类相反,我不需要,也不知道它是如何工作的)。
这是一个类似的问题和答案,但针对 PHP: php - simpleXML 如何访问与其他元素同名的特定元素? 我不知道与接受的答案等效的 Java 是什么。
提前致谢。
I'm trying to use SimpleXML to parse an XML document (an ItemLookupResponse
for a book from the Amazon Product Advertising API) which contains the following element:
<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>
My problem is that I don't know how to deal with the multiple possible Author
elements.
Here's what I have right now for the corresponding POJO (Plain Old Java Object), keeping in mind that it's not handling the case of multiple Author
s:
@Element
public class ItemAttributes {
@Element
public String Author;
@Element
public String Manufacturer;
@Element
public String Title;
}
(I don't care about the ProductGroup
, so it's not in the class -- I'm just setting SimpleXML's strict
mode to off
to allow for that.)
I couldn't find an example in the documentation that corresponded with such a case. Using an ElementList
with (inline=true)
seemed along the right lines, but I didn't see how to do it for String (as opposed to a separate Author class, which I have no need for and don't see how it would even work).
Here's a similar question and answer, but for PHP: php - simpleXML how to access a specific element with the same name as others? I don't know what the Java equivalent would be to the accepted answer.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注意,这只是阅读文档的结果(唯一的问题是它应该是 name="Author" 还是 entry="Author"):
N.B, this is just from reading the docs (the only question is if it should be name="Author" or entry="Author"):