Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML to Java object with recursive child definition [closed]

How can I convert this XML to Java objects?

 <template>
        <condition name="A">
            <li value="A">
                <condition name="B">
                    <li value="BB">Value B</li>
                    <li value="BBB">Value BBB</li>
                </condition>
            </li>
            <li>
                <condition name="C">
                    <li value="CC">Value CC</li>
                    <li value="CCC">Value CCC</li>
                    <li>
                        <condition name="D">
                            <li value="DD">Value DD</li>
                            <li value="DDD">Value DDD</li>
                         </condition>
                    </li>
                </condition>
            </li>
        </condition>
    </template>

Condition must have Li tag and li tag might have another condition and that condition will have li that might have another condition tag.

like image 540
Joseph Move Avatar asked Aug 29 '26 19:08

Joseph Move


1 Answers

You need to model the XML elements by corresponding Java classes with some @Xml... annotations. This is fairly straight-forward. The fact that there is recursion involved does not raise any additional problems.

A class modeling the <template> root element (with nested <condition> element):

@XmlRootElement(name = "template")
@XmlAccessorType(XmlAccessType.FIELD)
public class Template {

    @XmlElement(name = "condition")
    private Condition condition;

    // getters and setters
}

A class modeling the <condition> element (with nested <li> elements):

@XmlAccessorType(XmlAccessType.FIELD)
public class Condition {

    @XmlAttribute(name = "name")
    private String name;

    @XmlElement(name = "li")
    private List<ListItem> listItems;

    // getters and setters
}

A class modeling the <li> element (with nested <condition> element):

@XmlAccessorType(XmlAccessType.FIELD)
public class ListItem {

    @XmlAttribute(name = "value")
    private String value;

    @XmlElement(name = "condition")
    private Condition condition;

    // getters and setters
}

You can test all these classes with a conversion XML -> Java -> XML like this:

JAXBContext context = JAXBContext.newInstance(Template.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Template template = (Template) unmarshaller.unmarshal(new File("template.xml"));
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(template, System.out);
like image 109
Thomas Fritsch Avatar answered Aug 31 '26 14:08

Thomas Fritsch