Writing and Manipulating In-Memory XML Documents

I l @ ve RuBoard

One of the powerful features of the DOM is the ability to manipulate the XML document in memory. Let's now look at how to add, remove, and alter information in the DOM tree and how to write out the contents of the DOM once they've been changed.

Altering Content in a DOM Tree

The simplest thing you can do to alter the contents of a DOM tree is to delete part of it. The RemoveChild method of the XmlNode class allows you to remove a child of a given node. This operation will also delete any nodes below the given child. For example, the following code removes the first Sizes element in a CakeCatalog node together with the Option elements below it:

 XmlElementroot=doc.get_DocumentElement(); XmlNodeListnodes=root.GetElementsByTagName("Sizes",  "http://www.fourthcoffee.com/SchemaCakeCatalog.xsd"); XmlElementsizesElement=(XmlElement)nodes.get_ItemOf(0); sizesElement.get_ParentNode().RemoveChild(sizesElement); 

Attributes can be removed collectively or individually by using one of the methods of the XmlElement class. Remov eAttribute allows you to remove an attribute by name , RemoveAttributeAt removes an attribute by index, RemoveAttributeNode removes an attribute by reference, and RemoveAllAttributes clears all attributes of the element.

You can create new nodes to be added to a DOM tree using methods of the XmlDocument class. When you call type-specific creation methods, such as CreateElement and CreateTextNode , you supply the information to initialize the node. This information can include a name, namespace information, text content, and so on.

The following code shows a new element called Gateaux being created in the XML document, and some text content being added to that new element:

 Stringnamespace= "http://www.fourthcoffee.com/SchemaCakeCatalog.xsd"; XmlElementnewElement=doc.CreateElement("Gateaux",namespace); newElement.AppendChild(doc.CreateTextNode("Anewproductline!")); root.AppendChild(newElement); 

As you can see, when a new node is created, it is not attached to the document. You must use an appropriate method, such as AppendChild , to insert the node in the required place. XmlNode defines PrependChild and AppendChild to add a new child node at the start or end of the list of children, respectively. You can insert the new node relative to one of its siblings by passing that sibling to one of the InsertAfter or InsertBefore methods together with the new node. Another useful method is ReplaceChild , which allows you to replace a given child with a new one.

In addition to the type-specific creation methods, there is the generic CreateNode method. When you call CreateNode , you specify the type of node you want to create. (You cannot create a generic node!)

Note

Nodes are associated with a particular document regardless of whether they are currently attached to that document. You cannot create a node on one document and add it to another document.


When you create a new element, you can add a new attribute to it using the SetAttribute method as defined on the XmlElement class:

 Stringnamespace= "http://www.fourthcoffee.com/SchemaCakeCatalog.xsd"; XmlElementnewElement=doc.CreateElement("Gateaux",namespace); newElement.SetAttribute("flavor", "chocolate"); 

You can also use SetAttribute to change the value of an existing attribute.

As with the node creation methods, SetAttribute is overloaded and has several variations to support different namespace options. In all cases, if a new namespace is specified and no prefix is provided for it, a new prefix will be generated.

Making Substantial Changes to XML Documents

You can add or change large amounts of content in an XML document using the InnerXml property. The following code adds a Sizes element containing two Option elements within the newly created Gateaux element:

 XmlElementgateaux=doc.CreateElement("Gateaux"); ... XmlElementsizes=doc.CreateElement("Sizes",namespace); sizes.set_InnerXml("<OptionsizeInInches='10'/> <OptionsizeInInches='12'/>"); gateaux.AppendChild(sizes); 

All that has been explicitly created within the Gateaux element is a Sizes element. Setting the InnerXml of the Sizes element to a string containing the Option information then creates the Option elements. The DOM parses the given string and creates the required nodes. This approach requires a lot less programming than explicitly creating each required node in turn and adding them to the tree one by one. The best choice for your program will probably depend on whether you have the XML in a string format to begin with. (There's no point in creating a string yourself and then getting the DOM to parse it ”you might as well make the individual method calls.)

Similarly, if you want to add text to an element, you can set its InnerText property:

 XmlElementmessage=doc.CreateElement("Message",namespace); gateaux.AppendChild(message); message.set_InnerText("Sorry,writingmessagesongateauxistootricky!"); 

Warning

Even though using the InnerXml property to set a large amount of content in one operation can be convenient , you must take great care about namespaces. If you add some XML without namespace information to a document with namespaces set, you might not get what you expect. For example, if your DOM document has a default namespace and you add an element without specifying a namespace, it will not inherit the default namespace. Instead, the new element will explicitly have its namespace set to the empty namespace "". An in-depth discussion of this issue is outside the scope of this book, so for more information on how namespaces are treated in this case, see the .NET Framework class library documentation for the InnerXml property of the XmlDocument class.


All of the code shown so far is contained in the sample file ManipulateDOMDocument.jsl.

You can also create a completely new XML document using DOM. To do this, you just instantiate an XmlDocument and populate it using the methods you have seen in this section. Adding a child node to the XmlDocument creates the root node:

 XmlDocumentdoc=newXmlDocument(); XmlElementroot= (XmlElement)doc.AppendChild(doc.CreateElement("CakeCatalog")); root.set_InnerXml("<CakeTypestyle='celebration'filling='fruit' shape='round'><Message>Hi!</Message></CakeType>"); 

A complete application to create a new DOM document is contained in the sample file CreateDOMDocument.jsl. This sample file also shows you how to persist a DOM document, as discussed in the next section.

Writing Out the DOM Tree

Once you have edited the contents of your DOM tree (or created a new one), you'll probably want to persist these changes. To do this, you must save the DOM to a file or a stream. The XmlDocument class has a Save method that can write its XML representation to

  • A System.IO.Stream

  • A file name, as specified by a string

  • A TextWriter that wraps an appropriate destination

  • An XmlWriter that wraps an appropriate destination

If you create a new DOM document as shown previously, you can save it to a file by adding this line:

 doc.Save("BrandNewCatalog.xml"); 

You can omit part of a DOM tree using the WriteTo and WriteContentTo methods of the XmlNode class. Both of these methods take an XmlWriter that wraps up an appropriate destination. Again, referring to the newly created document, you can save just the Message element and its contents:

 XmlTextWriterwriter=newXmlTextWriter("JustTheMessage.xml", Encoding.get_UTF8()); root.get_FirstChild().get_FirstChild().WriteTo(writer); writer.Close(); 
I l @ ve RuBoard


Microsoft Visual J# .NET (Core Reference)
Microsoft Visual J# .NET (Core Reference) (Pro-Developer)
ISBN: 0735615500
EAN: 2147483647
Year: 2002
Pages: 128

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net