Search:

Custom Search
_________________________________________________________________

Tuesday, July 20, 2010

More XML options in C#


Continuing the xml posts, in this oportunity I will show you more options to create your XmlDocument.

Here we will see:

- Adding comment to the xml document (XmlComment)

- Adding fragment (XmlDocumentFragment)

- Creation of attributes (XmlAttribute)

- Adding information about the document Type (XmlDocumentType)

- And also, declarations and elements


Code:


XmlDocument xmlDoc = new XmlDocument();


XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

xmlDoc.AppendChild(xmlDec);


XmlElement root = xmlDoc.CreateElement("root-element");


//Adding info about the document type

XmlDocumentType docType = xmlDoc.CreateDocumentType("BOOKS", null, null, null);

xmlDoc.AppendChild(docType);


XmlAttribute xmlAtt = xmlDoc.CreateAttribute("attribute");

xmlAtt.Value = "value_for_xmlAtt";

root.SetAttributeNode(xmlAtt);

xmlDoc.AppendChild(root);


//Placing a comment in the Xml

XmlComment xmlComment = xmlDoc.CreateComment("First Book information");

root.AppendChild(xmlComment);


XmlElement book1 = xmlDoc.CreateElement("book-1");

book1.SetAttribute("name", "Harry Potter");

root.AppendChild(book1);


//Creating a Fragment

XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();

xmlDocFragment.InnerText = "---------Inner text-------";

xmlDoc.DocumentElement.AppendChild(xmlDocFragment);


XmlElement book2 = xmlDoc.CreateElement("book-2");

book2.SetAttribute("name", "Robles");

root.AppendChild(book2);


xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");


Output:



No comments: