Introduction
XName. The approach is to declare and initialize XNameXName
Example
The following example demonstrates this.
[c#]
XName Root = "Root";
XName Data = "Data";
XName ID = "ID";
XElement root = new XElement(Root,
new XElement(Data,
new XAttribute(ID, "1"),
"4,100,000"),
new XElement(Data,
new XAttribute(ID, "2"),
"3,700,000"),
new XElement(Data,
new XAttribute(ID, "3"),
"1,150,000")
);
Console.WriteLine(root);
This example produces the following output:
[xml]
<Root>
<Data ID="1">4,100,000</Data>
<Data ID="2">3,700,000</Data>
<Data ID="3">1,150,000</Data>
</Root>
The following example shows the same technique where the XML document is in a namespace:
[c#]
XNamespace aw = "http://www.adventure-works.com";
XName Root = aw + "Root";
XName Data = aw + "Data";
XName ID = "ID";
XElement root = new XElement(Root,
new XAttribute(XNamespace.Xmlns + "aw", aw),
new XElement(Data,
new XAttribute(ID, "1"),
"4,100,000"),
new XElement(Data,
new XAttribute(ID, "2"),
"3,700,000"),
new XElement(Data,
new XAttribute(ID, "3"),
"1,150,000")
);
Console.WriteLine(root);
This example produces the following output:
[xml]
<aw:Root xmlns:aw="http://www.adventure-works.com">
<aw:Data ID="1">4,100,000</aw:Data>
<aw:Data ID="2">3,700,000</aw:Data>
<aw:Data ID="3">1,150,000</aw:Data>
</aw:Root>
A more pertinent example is one where the content of the element is supplied by a query:
[c#]
XName Root = "Root";
XName Data = "Data";
XName ID = "ID";
DateTime t1 = DateTime.Now;
XElement root = new XElement(Root,
from i in System.Linq.Enumerable.Range(1, 100000)
select new XElement(Data,
new XAttribute(ID, i),
i * 5)
);
DateTime t2 = DateTime.Now;
Console.WriteLine("Time to construct:{0}", t2 - t1);
The above example performs better than the following, where names are not pre-atomized:
[c#]
DateTime t1 = DateTime.Now;
XElement root = new XElement("Root",
from i in System.Linq.Enumerable.Range(1, 100000)
select new XElement("Data",
new XAttribute("ID", i),
i * 5)
);
DateTime t2 = DateTime.Now;
Console.WriteLine("Time to construct:{0}", t2 - t1);