Search code examples
javaxmldomparsercomplextype

get the names of elements in a complex type(choice) from xml file


My xml file;

<?xml version="1.0" encoding="UTF-8"?>
<tns:military xmlns:tns="Military.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="Military.xsd Military.xsd ">
    <personel sicilNo="0" title="Bay">
        <militaryP>
            <class>
                <erbas>
                    <ad>aaa</ad>
                    <soyad>bbb</soyad>
                    <telefon>5556667788</telefon>
                    <yas>30</yas>
                    <rankErbas>Uzman</rankErbas>
                </erbas>
            </class>
            <department>tabur</department>
        </militaryP>
    </personel>
</tns:military>

based on xml schema;

<complexType name="tClass">
    <choice>
        <element name="erbas" type="tns:tErbas"></element>
        <element name="astSubay" type="tns:tAstsubay"></element>
        <element name="subay" type="tns:tSubay"></element>
        <element name="general" type="tns:tGeneral"></element>
    </choice>
</complexType>

I want to get name of class elements, how can i handle it? After i get it, i use it in switch/case statement. (in my example i want to get "erbas" )

switch(class) 
   case(erbas) ....
   case(astsubay) ...

Solution

  • String class_ = elem.getElementsByTagName("class").item(0).
    getChildNodes().item(1).getNodeName();
    

    I add this code. It works. But i dont understand how it works :) when i change to "item(1)" from item(0), it gives child element's name.