英文:
Using Jackson to parse XML with repeated element
问题
我正在寻找一种使用Jackson解析具有重复元素的XML结构的简单方法。这里是一个简化的示例:
<root>
<a>
<x>
<b>some content</b>
<c>some content</c>
</x>
<x>
<b>some content</b>
<c>some content</c>
</x>
...
<x>
<b>some content</b>
<c>some content</c>
</x>
</a>
... 其他一些内容 ...
</root>
我想要将所有的 x
元素收集到一个列表或数组中。问题在于,当使用类似以下的内容时:
XmlMapper().readTree(xml).get("a").fields()
结果只包含最后一个 x
的实例,所以看起来某个映射键被覆盖了。有一种解决方法是使用 JsonParser
,例如:XmlMapper().createParser(xml)
,但这有点麻烦。
有更好的方法吗?
编辑
根据自述文件中的“已知限制”部分,我认为XML在Jackson中似乎是一个二等公民。我接受@galuszkak的答案,因为情况就是这样,但在我看来,当开发人员调用 XmlMapper().readTree(xml)
时,他们并不希望XML处理被塞进JSON处理模型中,带来了这种方法的限制。
英文:
I am looking for a simple way to parse an XML structure with a repeated element using Jackson. Here is a simplified example:
<root>
<a>
<x>
<b>some content</b>
<c>some content</c>
</x>
<x>
<b>some content</b>
<c>some content</c>
</x>
...
<x>
<b>some content</b>
<c>some content</c>
</x>
</a>
... some other content ...
</root>
I would like to collect all the x
elements in a list or array The problem is that when using something like:
XmlMapper().readTree(xml).get("a").fields()
the result contains only the last instance of x
so it looks like some map key gets overwritten. There is a solution using JsonParser
e.g.: XmlMapper().createParser(xml)
but it's a bit icky.
Is there a better way?
Edit
The way I read the "Known Limitations" section in the README , XML seems to be a second class citizen in Jackson. I accept @galuszkak 's answer as it is what it is , but to my mind when a developer invokes XmlMapper().readTree(xml)
they do not expect XML processing to be shoehorned into JSON processing model with the limitations that come with that approach.
答案1
得分: 0
这里提到的问题在这个Github问题中有描述:
https://github.com/FasterXML/jackson-dataformat-xml/issues/187
基本上出现的情况是,Jackson正在将XML树结构转换为JsonNode数据模型,但这不起作用,因为它不受支持。
在那个Github问题中描述了两个选项:
- 将此XML完全转换为JSON(来自Github上的@cawena的回答)
- 或者,如果您了解您的数据结构,可以使用p0sitron提供的答案:
代码:
List<List<JsonNode>> elA = xmlMapper.readValue(xml, new TypeReference<List<List<JsonNode>>>() { });
assertEquals(3, elA.get(0).size());
英文:
The problem mentioned here is described in this Github issue:
https://github.com/FasterXML/jackson-dataformat-xml/issues/187
Basically what is happening is that Jackson is translating XML tree structure in JsonNode data model and this will not work as it's not supported.
There is 2 options described in that Github issue:
- Fully transform this XML to JSON (answer from @cawena on Github)
- Or if you know your data structure to just use answer from p0sitron which is:
Code:
List<List<JsonNode>> elA = xmlMapper.readValue(xml, new TypeReference<List<List<JsonNode>>>() { });
assertEquals(3, elA.get(0).size());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论