LINQ to XML : Creating complete XML document
LINQ to XML API allows us to create complete XML document as expected with all the elements. So this X-DOM has everything as you expect.
Simple sample looks like,
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-16", "true"),
new XProcessingInstruction("test", "value"),
new XComment("This is comment by you"),
new XElement("Employees",
new XElement("Employee",
new XAttribute("id", "EMP001"),
new XElement("name", "Wriju"),
new XCData("~~~~~~~XML CDATA~~~~~~~~"))));
By calling Save method of XDocument (actually of XContainer) you can save it to a physical file. And the file will look like,
<?xml version="1.0" encoding="utf-16" ?>
<?test value?>
<!-- This is comment by you -->
<Employees>
<Employee id="EMP001">
<name>Wriju</name>
<![CDATA[ ~~~~~~~XML CDATA~~~~~~~~]]>
</Employee>
</Employees>
To me this looks like more aligned to the human thinking mechanism.
Namoskar!!!
Comments
Anonymous
February 28, 2008
PingBack from http://www.biosensorab.org/2008/02/28/linq-to-xml-creating-complete-xml-document/Anonymous
February 28, 2008
LINQ to XML API allows us to create complete XML document as expected with all the elements. So thisAnonymous
February 28, 2008
The new C# LINQ to XML syntax is nice, but the VB syntax is IMHO even more readable: Dim xmlDoc As XDocument = _ <?xml version="1.0" encoding="utf-16"?> <!-- This is comment by you --> <Employees> <Employee id="EMP001"> <name>Wriju</name> <![CDATA[ ~~~~~~~...~~~~~~~~]]> </Employee> </Employees>Anonymous
March 24, 2008
@Andre, Yes VB rocksAnonymous
August 06, 2008
Perhaps I am missing the answer to the obvious question here. Why would you hardcode your XML document within your code instead of storing it in a file. The latter option allows you to tweak/update your XML template without having to recompile code. That it looks intuitive seems to be of secondary importance?Anonymous
September 17, 2008
Abraham, You might need to create it dynamically based on criteria unknown until runtime (user input, database values, etc...).Anonymous
December 01, 2008
Hi, its possible insert cdata tag within xattribute ? thanksAnonymous
February 10, 2009
Yes, It's called Visual Basic for a reason.Anonymous
May 16, 2010
In this case Employees would likely be a list of employees...in vb you would simply do a for each directly in the embeded xml to enumerate all of the employees Dim xmlDoc As XDocument = _ <?xml version="1.0" encoding="utf-16"?> <!-- This is comment by you --> <Employees> <%= From e In [your employees] Select _ <Employee id=<%[value]%>> <name><%[value]%></name> <![CDATA[ ~~~~~~~...~~~~~~~~]]> </Employee> _ %> </Employees> how would this be done in C#?