XAttribute, XComment, XDeclaration, XDocument,
XElement, XName/XNamespace
Creating XML:
XElement
inventory =
new
XElement("Inventory",
new
Xelement ( "Car", new XAttribute("ID",
"1"),
new
XElement("Color", "Green"),
new
XElement("Make", "BMW"),
new
XElement("PetName", "Stan")
)
);
A Complete XML Document:
XDocument inventoryDoc =
new
XDocument(
new
XDeclaration("1.0", "utf-8", "yes"),
new
XComment("Current Inventory of AutoLot"),
new
XElement("Inventory",
new
XElement("Car", new XAttribute("ID", "1"),
new
XElement("Color", "Green"),
new
XElement("Make", "BMW"),
new
XElement("PetName", "Stan")
),
new
XElement("Car", new XAttribute("ID", "2"),
new
XElement("Color", "Pink"),
new
XElement("Make", "Yugo"),
new
XElement("PetName", "Melvin")
)
)
);
inventoryDoc.Save("SimpleInventory.xml");
Converting Arrays to XML using Linq:
var data =
new [] {
new
{ PetName = "Melvin", ID = 10 },
new
{ PetName = "Pat", ID = 11 }
};
// Now enumerate over the array to build an Xelement.
XElement vehicles =
new XElement("Inventory",
from
c in data
select
new XElement("Car",
new
XAttribute("ID", c.ID),
new
XElement("PetName", c.PetName)
)
);
XElement temp = XElement.Parse(
@“<Inventory>
<Car
carID ="0">
<Make>Ford</Make>
<Color>Blue</Color>
<PetName>Chuck</PetName>
</Car>
<Car
carID ="1">
<Make>VW</Make>
<Color>Silver</Color>
<PetName>Mary</PetName>
</Car>
<Car
carID ="2">
<Make>Yugo</Make>
<Color>Pink</Color>
<PetName>Gipper</PetName>
</Car>
</Inventory>”
);
Linq expressions over XML:
from pn in temp.Descendants("PetName")
select
pn.Value;
AND
from c in doc.Descendants("Make")
where c.Value
== "Ford"
select c;