mardi 31 janvier 2017

How to use reflection to parse xml to set java bean

I have an XML of this sort, with repeating elements(repetition varies).

  <Agents>
        <Agent>
            <a>data</a>
            <b>data</b>
            <c>
               <ca>data</ca>
               <cb>data</cb>
            </c>
            <c>
               <ca>data</ca>
               <cb>data</cb>
            </c>
        </Agent>
        <Agent>
            <a>data</a>
            <b>data</b>
            <c>
               <ca>data</ca>
               <cb>data</cb>
            </c>
            <c>
               <ca>data</ca>
               <cb>data</cb>
            </c>
        </Agent>
        <id>data</id>
        <name>data</name>
</Agents>

For parsing the above XML to set the java bean. Java code written is

NodeList nodeList = document.getElementsByTagName("*");

        for (int i = 0; i < nodeList.getLength(); i++) {
            node = nodeList.item(i);
            if ((node.getNodeType() == Node.ELEMENT_NODE)){
               if (node is an array element){

How would I know which object to get ????

            object (???)
            get setter using reflection.
            invoke data 
       }else{
          object is the mainBean.
          get setter using reflection.
          invoke data.
       }
    }
}

P.S:

  • I have stored the arrayElement tag names in a Map

  • Example: To set ca,cb I need the object of beanC. I have to use the same object to setAgent in BeanAgent.

  • And how can we deal when I have an array in array. like C has another element ca which is repeating.

I have tried my best to explain the problem I have been facing. Please comment if you need any more details to understand my problem. Thanks.





Aucun commentaire:

Enregistrer un commentaire