XmlMapper用重复元素编写XML

时间:2019-01-09 18:11:04

标签: java xmlmapper

我正在使用XmlMapper使用POJO编写XML文件。 我希望我的xml看起来像:

<?xml version="1.0" encoding="ISO-8859-1"?>
<document>
<section name="introduction">
  <paragraph>
    <word>1</word>
    <word>2</word>
  </paragraph>
  <paragraph>
    <word>3</word>
    <word>4</word>
  <paragraph>
</section>
<section name="abstract">
 <paragraph>
    <word>1.1</word>
    <word>2.1</word>
  </paragraph>
  <paragraph>
    <word>3.1</word>
    <word>4.1</word>
  <paragraph>
</section>
</document>

我在pojo中使用了以下代码,该代码列出了列表。每个列表都是一个段落。

@JacksonXmlElementWrapper(localName = "paragraph")
    @JacksonXmlProperty(localName = "word")
    public List<List<String>> getParagraph()
    {
        List<List<String>> paragraphList = new ArrayList<List<String>>();
        String[] splited = sectionText.split("\n");
        for (String paragraph : splited)
        {
            String[] splittedWords = paragraph.split("\\s+");
            paragraphList.add(Arrays.asList(splittedWords));
        }
        return paragraphList;
    }

但这给了我以下输出:

<?xml version="1.0" encoding="ISO-8859-1"?>
<document>
<section name="introduction">
  <paragraph>
    <word>1</word>
    <word>2</word>
    <word>3</word>
    <word>4</word>
  <paragraph>
</section>
<section name="abstract">
 <paragraph>
    <word>1.1</word>
    <word>2.1</word>
    <word>3.1</word>
    <word>4.1</word>
  <paragraph>
</section>
</document>

我需要在每个列表结束后放置段落标识符。我可以使用列表以外的其他东西

1 个答案:

答案 0 :(得分:1)

(更新后)... 您似乎错过了需要Paragraph Pojo的观点。

然后,您的Section Pojo必须具有List<Paragraph>属性,而Paragraph Pojo必须具有List<Word>属性