XElement and XAttribute are the two very important classes available in System.Xml.Linq.dll assembly. Using these two classes you can do lot of things in the LINQ to XML world. I will show you step by step how,
For just an element
XElement _root = new XElement("root");
_root.Save(fileName);
And the output will look like,
<?xml version="1.0" encoding="utf-8" ?>
<root />
Now if you want to add child to the root,
XElement _child = new XElement("child");
_root.Add(_child);
The generated XML would look like,
<root>
<child />
</root>
This work like DOM.
Now the .Add() method allows you pass values in form of object. So we can pass anything there,
XAttribute attr = new XAttribute("attrbt", 2008);
_root.Add(attr);
The XML view will be like,
<root attrbt="2008">
Now another interesting part is that the Add() method not only takes an object it also accepts array of objects. So you ideally do not have to call .Add() multiple times.
With the same output as before you can create you code,
_root.Add(_child, attr);
For more child you can simply keep on adding elements to the Add() method separated by comma.
XElement _child1 = new XElement("child1");
XElement _child2 = new XElement("child2");
XElement _child3 = new XElement("child3");
_root.Add(_child1, _child2, _child3, attr);
Now the output goes,
<child1 />
<child2 />
<child3 />
By using List<T> you can elegantly add elements to the root. Same output for this code,
List<XElement> childs = new List<XElement>
{
new XElement("child1"),
new XElement("child2"),
new XElement("child3")
};
_root.Add(childs, attr);
Now with all these options you can go ahead and use the constructor to add elements and attribute to your root.
So if I want to generate previous XML in one liner way, I could do this,
XElement _root = new XElement("root",
new List<XElement>
},
new XAttribute("attrbt", 2008));
//_root.Add(childs, attr);
Now I do not require Add() method at all.
Hope this gives you the idea about the basics of XElement and XAttribute. Thanks to Mike Taulty , I have learnt this from one of his finest demos.
Namoskar!!!
XElement and XAttribute are the two very important classes available in System.Xml.Linq.dll assembly
Welcome to the forty-first Community Convergence. The big news this week is that we have moved Future
a ver ayuda con esta consulta no me sale
var result = (from c in bdmia.misdatos
where c.idtbl == codFilial &&
c.data.Elements("Filial").Attributes("Nombre").First().Value=="Filial1"
select c);
help
@NInoska
Please drop me an email through blog with the actual problem