Below is the XML format needs to be parsed with apex:
<?xml version="1.0" encoding="UTF-8"?>
<Parents>
<SubParent>
<SuperParent>
<Child>
<SubChild>
<SuperChild>
<name>Test</name>
<code>123</code>
</SuperChild>
</SubChild>
</Child>
</SuperParent>
</SubParent>
<SubParent>
<name>Playstation</name>
<code>PS</code>
</SubParent>
</Parents>
I am pasing this XML in apex as follows:
Dom.Document doc = new Dom.Document();
doc.load(xml);
for(Dom.XMLNode child: doc.getRootElement().getChildElements() ){
if(child.getName() == 'SubParent'){
for(Dom.XMLNode bchild : child.getChildElements()){
if(bchild.getName() == 'SuperParent'){
for(Dom.XMLNode cChlild : bchild.getChildElements()){
if(cChlild.getName() == 'Child'){
for(Dom.XMLNode eChlild : cChlild.getChildElements()){
if(cChlild.getName() == 'SubChild'){
for(Dom.XMLNode eChlild : cChlild.getChildElements()){
if(cChlild.getName() == 'SuperChild'){
//Business logic
}
}
}
}
}
}
}
}
}
}
I want guidance that can I parse these type of XML's without using nested for loops. If yes then in what way?
Best Answer
My preferred approach to this is to have a class with a set of inner classes that mimic your xml schema. Doing this allows you to break up the parsing work, keeping only a small portion of the overall xml parsing in each class.
This approach doesn't really remove any loops in the end (a nested data structure is pretty much a guarantee that you'll need to use nested loops), but it re-arranges them to be (in my opinion) much easier to digest and maintain.
The following is taken from the question and my answer on Convert Apex XML response into JSON Format?
A portion of the xml from that question
The corresponding Apex to parse that.
Summarizing what I did there:
List
of that child tagIt's worth noting that this approach implements a depth-first traversal of your xml. For apex classes like this, it seems like the limit of function calls on the stack is 1,000. I don't think you can ever get close to that using the
DOM
classes though, as the documentation onDOM.Document
states that it only allows you to parse xml up to 50 nodes deep.