13.07.2015 Views

Applied XML Programming for Microsoft .NET.pdf - Csbdu.in

Applied XML Programming for Microsoft .NET.pdf - Csbdu.in

Applied XML Programming for Microsoft .NET.pdf - Csbdu.in

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

If you use a namespace, you might reasonably want to use a prefix too. To specify anamespace prefix, resort to another overload <strong>for</strong> the CreateElement method <strong>in</strong> whichyou pass <strong>in</strong> the order, the prefix, the local name of the element, and the namespaceURI, as shown here:XmlNode root = doc.CreateElement("d", "folders", "urn:d<strong>in</strong>o-e");The node <strong>XML</strong> code changes to this:At this po<strong>in</strong>t, to also qualify the successive nodes with this namespace, callCreateElement with the prefix and the URI, as shown here:n = doc.CreateElement("d", "folder", "urn:d<strong>in</strong>o-e");NoteBear <strong>in</strong> m<strong>in</strong>d that although all the CreateXXX methods available <strong>in</strong>the XmlDocument class can create an <strong>XML</strong> node, that node is notautomatically added to the <strong>XML</strong> DOM. You must do that explicitlyus<strong>in</strong>g one of the several methods def<strong>in</strong>ed to extend the currentDOM.Append<strong>in</strong>g AttributesAn attribute is simply a special type of node that you create us<strong>in</strong>g the CreateAttributemethod. The method returns an XmlAttribute object. The follow<strong>in</strong>g code shows how tocreate a new attribute named path and how to associate it with a parent node:XmlAttribute a;a = doc.CreateAttribute("path");a.Value = path;node.Attributes.SetNamedItem(a);Like CreateElement, CreateAttribute too allows you to qualify the name of the attributeus<strong>in</strong>g a namespace URI and optionally a prefix. The overloads <strong>for</strong> both methods havethe same signature.You set the value of an attribute us<strong>in</strong>g the Value property. At this po<strong>in</strong>t, however, theattribute node is not yet bound to an element node. To associate the attribute with anode, you must add the attribute to the node's Attributes collection. The SetNamedItemmethod does this <strong>for</strong> you. The follow<strong>in</strong>g code shows the f<strong>in</strong>alized version of the loopthat creates the <strong>XML</strong> file <strong>for</strong> our example:<strong>for</strong>each (DirectoryInfo d <strong>in</strong> dir.GetDirectories()){n = doc.CreateElement("folder");a = doc.CreateAttribute("name");a.Value = d.Name;n.Attributes.SetNamedItem(a);a = doc.CreateAttribute("created");a.Value = d.CreationTime.ToStr<strong>in</strong>g();n.Attributes.SetNamedItem(a);192

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!