Manually building an XmlDocument

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,
Simple question this one.

How can I manually build a simple xmldocument in code.
Lets say for example

<Products>
<Boat id="1">
<Price>9000</Price>
</Boat>
</Products>

thank you very much.
 
Hi,

You need to use System.XML namespace for that. Here is a small example of
creating an XML document through C#:
using System;
using System.Xml;

namespace Test
{
class MainClass
{
XmlDocument xmldoc;
XmlNode xmlnode;
XmlElement xmlelem;
XmlElement xmlelem2;
XmlText xmltext;
static void Main(string[] args)
{
MainClass app=new MainClass();
}
public MainClass() //constructor
{
xmldoc=new XmlDocument();
//let's add the XML declaration section
xmlnode=xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"","");
xmldoc.AppendChild(xmlnode);
//let's add the root element
xmlelem=xmldoc.CreateElement("","ROOT","");
xmltext=xmldoc.CreateTextNode("This is the text of the root element");
xmlelem.AppendChild(xmltext);
xmldoc.AppendChild(xmlelem);
//let's add another element (child of the root)
xmlelem2=xmldoc.CreateElement("","SampleElement","");
xmltext=xmldoc.CreateTextNode("The text of the sample element");
xmlelem2.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);
//let's try to save the XML document in a file: C:\pavel.xml
try
{
xmldoc.Save("c:\mydoc.xml");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}

Hope this helps.

Thanks

Mona[Grapecity]
 
CodeRazor said:
Hello,
Simple question this one.

How can I manually build a simple xmldocument in code.
Lets say for example

<Products>
<Boat id="1">
<Price>9000</Price>
</Boat>
</Products>

thank you very much.

if you are just interested in the xml *text* (at first), you can use this:

----------------------
using System.IO;
using System.Text;
using System.Xml;


StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented; // optional

xw.WriteStartElement("Products");
xw.WriteStartElement("Boat");
xw.WriteAttributeString("id", "1");
xw.WriteElementString("Price", "9000");
xw.WriteEndElement();
xw.WriteEndElement();

Console.WriteLine(sb.ToString()); // or any other way to "use" the xml-text
 
Back
Top