I have the following XML:
<docs>
<doc>
<person>
<name>John Doe</name>
<description>
<age>23</age>
<alias>M C</alias>
</description>
<description>
<age>24</age>
<alias>John</alias>
</description>
</person>
<doc>
<doc>
<person>
<name>John Doe</name>
<description>
<age>24</age>
<alias>Steve</alias>
</description>
</person>
<doc>
</docs>
I do not have control over the xml. All I get is such xml documents and xpath for the elements. I have write a java program to read the data and convert it to Json object. I am using xPath and dom parser and since we get the xPath for xml, I thought I will make use of it as the xPath may change in the future. So I had xPath for all the elements in the property file, so if there is a change I will have minimum changes in the program. And unfortunately the program should be case insensitive, so I used translate(xPath) to handle it. I have following class
public class Person {
private List<String> name;
private List<String> age;
private List<String> alias;
//getter and setter
}
The issue is having multiple doc nodes and each can have multiple age and alias elements. Earlier it was not the requirement so I used XPath to get the text but now I can't use it because the xPath of //person/description will return 3 nodes, 2 from first doc and one from another doc. The issue is I need to differentiate the description tag to say whether it is coming from first doc or the other one. So the final Json will look like
{
"docs":
{
"doc":
[
{
"description":
[
{
"age": 23,
"alias": "M C"
},
{
"age": 24,
"alias": "John"
}
]
},
{
"description":
[
{
"age": 24,
"alias": "Steve"
}
]
}
]
}
}
So all I could think of is compile the xPath expression - //docs/doc, I will have 2 nodes at this point and get the child nodes and loop through by getting the child nodes and do something like if
element.getTagName().equalsIgnoreCase("age")
then add to age list and then do like list of lists , so I will end up having
docs[[[23, "M C"],[24, "John"]],[[24, "Steve"]]]
Any better ideas?