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!!!
PingBack from http://www.biosensorab.org/2008/02/28/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
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"?>
<![CDATA[ ~~~~~~~...~~~~~~~~]]>
@Andre,
Yes VB rocks
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?
Abraham,
You might need to create it dynamically based on criteria unknown until runtime (user input, database values, etc...).
Hi,
its possible insert cdata tag within xattribute ?
thanks
Yes, It's called Visual Basic for a reason.
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
<%= From e In [your employees] Select _
<Employee id=<%[value]%>>
<name><%[value]%></name>
</Employee> _
%>
how would this be done in C#?