Click to See Complete Forum and Search --> : xmldocument and nodes


Visslan
February 15th, 2009, 02:20 PM
Hello!

I want to make a xmlstructure like this:


<?xml version="1.0" ?>
<ROOT>
This is the text of the root element
<SupplierID>
Supplier id
<SupplierName>Supplier name</SupplierName>
</SupplierID>
</ROOT>


This is my code so far:


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("", "SupplierID", "");
xmltext = xmldoc.CreateTextNode("Supplier id");
xmlelem2.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);


now my problem I don't know how to add a node into my first node SupplierID?

BigEd781
February 15th, 2009, 05:38 PM
Try using the CreateStartElement() method when creating a parent node like that. Then use CreateElement() to append elements to the current parent node. Don't forget to call EndStartElement() for each CreateStartElement() call.

cilu
February 16th, 2009, 02:02 AM
If you need to serialize/unserialize some data structures, you can use XmlSerializer. There is also a new set of classes for handling XML documents, XElement. For simple files like yours I think it's much easier to use.