Element nodes are created using the CreateElement() method. The node is first configured with all of its expected child nodes and then added to the document. For example, to create an element named bookstore, you need to do the following. |
XmlNode bookstoreNode = doc.CreateElement(“bookstore”); |
Note that although all the CreateXXX() methods available in the XmlDocument class can create an XML node, that node is not automatically added to the XML DOM. You must do that explicitly using the |
AppendChild() method. |
Appending Attributes |
An attribute is simply a special type of node that you create using the CreateAttribute() method of the XmlDocument class. The return value of this method is an XmlAttribute object. The following code shows how to create a new attribute named genre and how to associate it with a parent book node: |
XmlAttribute genreAttribute = doc.CreateAttribute(“genre”); genreAttribute.Value = txtGenre.Text; bookNode.Attributes.Append(genreAttribute); |
Similar to CreateElement(), CreateAttribute() too allows you to qualify the name of the attribute using a namespace URI and optionally a prefix. The overloads for both methods have the same signature. |
You set the value of an attribute using the Value property. At this point, however, the attribute node is not yet bound to an element node. To associate the attribute with a node, you must add the attribute to the node’s Attributes collection. The Append() method of the XmlAttributeCollection class does this for you. |
Persisting Changes |
The final step in saving the XML document you have created is to save the document, as shown here: |
doc.Save(xmPath); |
To persist all the changes to storage medium, you call the Save() method, which contains four overloads, shown here: |
Save(Stream): Saves the XML document to the specified stream |
Save(string): Saves the XML document to the specified file |
Save(TextWriter): Saves the XML document to the specified TextWriter |
Save(XmlWriter): Saves the XML document to the specified XmlWriter |
As you can see, you can save the XML document to a disk file as well as to an output stream, including network and compressed streams. You can also integrate the class that manages the document with other .NET Framework applications by using writers, and you can combine more XML documents using, in particular, XML writers. For example, the following code snippet saves the XML document to a string using a StringWriter object. (The StringWriter class is derived from TextWriter, which writes data to a string.) |
learn guitarphysics learnteliphonyxmlphysicsenjoylife