osagie
osagie

Reputation: 269

How to dynamically populate XElement (linq to xml)

Is there a way I can dynamically add a new XElement to form child nodes as in the example below?

XElement xEl = new XElement(
                new XElement("Root",
                  // ** Is there a way I can do this:  
                 //  for(MyObject mObj in myObjects) {
                 //     if (IsXmlObj(mObj)){
                 //         new XElement(mObj.Name, mObj.Value);
                 //       }
                 //   }
                );

I would like to iterate through an object list to form the sub nodes.

What if I now modify the iterating part to become:

 //  for(MyObject mObj in myObjects) {
                 //     if (IsXmlObj(mObj)){
                 //         if (mObject.Name=="Small"){ mObject.Name="Big";}
                 //         new XElement(mObj.Name, mObj.Value);
                 //       }
                 //   }

Upvotes: 1

Views: 77

Answers (1)

ocuenca
ocuenca

Reputation: 39326

Use a Select this way:

var xEl = new XElement("Root",myObjects.Where(mObj=>IsXmlObj(mObj))
                                       .Select(mObj=> new XElement(mObj.Name, mObj.Value)));

Upvotes: 2

Related Questions