javaxmlmapper

XmlMapper to write XML with repeating element


I am using XmlMapper to write a XML file using POJO. I want my xml to look like :

<?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>

I used following code in my pojo, which make a list of list. Each list is a pragraph.

@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;
    }

But this give me following output:

<?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>

I need to put the paragraph identifier after each list ends. Shall I use something else other than list


Solution

  • (after your update)... It looks like you missed a point that you need Paragraph Pojo.

    Then your Section Pojo must have a List<Paragraph> property and Paragraph Pojo must have a List<Word> property