Optimizing recursive XML build

juniors117

New Member
I have some code that I wrote to build up an XML recursively, and it works very good as intended except one thing, that is not so generic.The array is \[code\]string[] countries= string[]{ ..... }\[/code\]My idea to have is following, if an array contains only 1 string than it should be:\[code\]<Where> <Eq> <FieldRef /> <Value /> </Eq></Where>\[/code\]If there are more then one, than it should contain \[code\]<OR>\[/code\], but for the last string value should be in the same OR: so basically it would be something like that for 4 items:\[code\]<Where> <Or> <Eq> <FieldRef Name="Title" /> <Value Type="Text">Canada</Value> </Eq> <Or> <Eq> <FieldRef Name="Title" /> <Value Type="Text">New Zealand</Value> </Eq> <Or> <Eq> <FieldRef Name="Title" /> <Value Type="Text">United States</Value> </Eq> <Eq> <FieldRef Name="Title" /> <Value Type="Text">Switzerland</Value> </Eq> </Or> </Or> </Or></Where>\[/code\]Everything is nested.Here is my code, it works great for the multi array but not for a single result:\[code\]private XElement Recursion(XElement parentElement, int counter) { if (counter == 0) { return parentElement; } XElement orElement = new XElement("Or"); XElement eqElement = new XElement("Eq"); XElement fieldElement = new XElement("FieldRef"); XAttribute nameAttribute = new XAttribute("Name", "Title"); fieldElement.Add(nameAttribute); XElement valueElement = new XElement("Value", Countries[counter]); XAttribute typeAttribute = new XAttribute("Type", "Text"); valueElement.Add(typeAttribute); eqElement.Add(fieldElement); eqElement.Add(valueElement); orElement.Add(eqElement); if (counter == 1) { eqElement = new XElement("Eq"); valueElement = new XElement("Value", Countries[0]); valueElement.Add(typeAttribute); eqElement.Add(fieldElement); eqElement.Add(valueElement); orElement.Add(eqElement); } XElement lastOrElement = parentElement.Descendants("Or").FirstOrDefault(or => !or.Descendants("Or").Any()); if (lastOrElement == null) { parentElement.Add(orElement); } else { lastOrElement.Add(orElement); } return Recursion(parentElement, --counter); }}\[/code\]
 
Back
Top