【问题标题】:How to read a xml having list of elements not enclosed in parent tag [duplicate]如何读取具有未包含在父标记中的元素列表的xml [重复]
【发布时间】:2022-01-20 10:52:18
【问题描述】:

如何读取包含未包含在 Xml 文件的父标记示例中的元素列表的 xml,如下所示。在此示例中,它是未包含在任何父标记中的学生列表。请帮助我阅读此文件并使用 Jackson 解析器提取数据

<Student>
    <name>John</name>
    <class>
        <section>A</section>
    </class>
    <subject>English</subject>
</Student>
<Student>
    <name>Johny</name>
    <class>
        <section>B</section>
    </class>
    <subject>Science</subject>
</Student>
<Student>
    <name>Rock</name>
    <class>
        <section>C</section>
    </class>
    <subject>Mathematics</subject>
</Student>

【问题讨论】:

标签: java xml spring jackson


【解决方案1】:

在您的 POJO 类(Example.class)中,定义未包含在任何父标记中的学生列表,如下所示。

@JacksonXmlElementWrapper(useWrapping = false)
private List<Student> students = new ArrayList<>();

现在在你解析这个 xml 的另一个类中使用这个

String xmlString = "<Student>...</Student>";
XmlMapper xmlMapper = new XmlMapper();
Example value = xmlMapper.readValue(xmlString, Example.class);

在 pom.xml 中添加 maven 依赖

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.11.1</version>
</dependency>

【讨论】:

  • 感谢您的建议...如果我按照上面建议的相同程序进行操作,我将得到空的 Student arrayList 而没有填充数据。
猜你喜欢
  • 2019-07-09
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 2018-10-08
相关资源
最近更新 更多