Advertisement
ivandrofly

Programmatically creating a new XML document

Apr 25th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1.  
  2. using System;
  3. using System.Xml;
  4.  
  5. public class GenerateXml {
  6.     private static void Main() {
  7.         XmlDocument doc = new XmlDocument();
  8.         XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
  9.         doc.AppendChild(docNode);
  10.  
  11.         XmlNode productsNode = doc.CreateElement("products");
  12.         doc.AppendChild(productsNode);
  13.  
  14.         XmlNode productNode = doc.CreateElement("product");
  15.         XmlAttribute productAttribute = doc.CreateAttribute("id");
  16.         productAttribute.Value = "01";
  17.         productNode.Attributes.Append(productAttribute);
  18.         productsNode.AppendChild(productNode);
  19.  
  20.         XmlNode nameNode = doc.CreateElement("Name");
  21.         nameNode.AppendChild(doc.CreateTextNode("Java"));
  22.         productNode.AppendChild(nameNode);
  23.         XmlNode priceNode = doc.CreateElement("Price");
  24.         priceNode.AppendChild(doc.CreateTextNode("Free"));
  25.         productNode.AppendChild(priceNode);
  26.  
  27.         // Create and add another product node.
  28.         productNode = doc.CreateElement("product");
  29.         productAttribute = doc.CreateAttribute("id");
  30.         productAttribute.Value = "02";
  31.         productNode.Attributes.Append(productAttribute);
  32.         productsNode.AppendChild(productNode);
  33.         nameNode = doc.CreateElement("Name");
  34.         nameNode.AppendChild(doc.CreateTextNode("C#"));
  35.         productNode.AppendChild(nameNode);
  36.         priceNode = doc.CreateElement("Price");
  37.         priceNode.AppendChild(doc.CreateTextNode("Free"));
  38.         productNode.AppendChild(priceNode);
  39.  
  40.         doc.Save(Console.Out);
  41.     }
  42. }
  43.  
  44. See output: http://www.java2s.com/Code/CSharpImages/ProgrammaticallycreatinganewXMLdocument.PNG
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement