Unmarshal JAXB элементы с тем же тегом, что и в parent и child - PullRequest
0 голосов
/ 31 мая 2019

Я хочу отменить вывод ниже XML, используя JAXB, чтобы я мог перейти к дочернему узлу, чтобы прочитать элемент тега leaf.

<root>
   <concept name="GrandParent">
    <concept name="Parent1">
        <concept name="Child11">
            <input>some child input11</input>
        </concept>
        <concept name="Child12">
            <input>some child input21</input>
        </concept>
    </concept>      
    <concept name="Parent2">
            <concept name="Child21">
                <input>some child input21</input>
            </concept>
            <concept name="Child22">
                 <input>some child input22</input>
            </concept>
    </concept>
   </concept>   
</root> 

Я ожидаю, что число детей для parent1 и parent 2.

1 Ответ

0 голосов
/ 31 мая 2019

Вам нужно построить модель, аннотировать с помощью JAXB аннотации и анализировать XML. Смотрите ниже пример:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.File;
import java.util.List;

public class XmlMapperApp {

    public static void main(String[] args) throws Exception {
        File xmlFile = new File("./resource/test.xml").getAbsoluteFile();

        JAXBContext jaxbContext = JAXBContext.newInstance(Roots.class);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        Concept root = ((Roots) unmarshaller.unmarshal(xmlFile)).getConcept();
        root.getConcept().forEach(System.out::println);
    }
}

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
class Roots {

    private Concept concept;

    // getters, setters, toString
}

@XmlType(name = "concept")
@XmlAccessorType(XmlAccessType.FIELD)
class Concept {

    @XmlAttribute
    private String name;

    @XmlElement
    private List<Concept> concept;

    @XmlElement
    private String input;

    // getters, setters, toString
}

Над отпечатками кодов:

Concept{name='Parent1', concept=[Concept{name='Child11', concept=null, input='some child input11'}, Concept{name='Child12', concept=null, input='some child input21'}], input='null'}
Concept{name='Parent2', concept=[Concept{name='Child21', concept=null, input='some child input21'}, Concept{name='Child22', concept=null, input='some child input22'}], input='null'}
...