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.

Figure 4-14: The code can be used to change the value of the <strong>for</strong>ecolor attribute from blueto black.Add<strong>in</strong>g and Delet<strong>in</strong>g NodesA source <strong>XML</strong> document can also be easily read and modified by add<strong>in</strong>g or delet<strong>in</strong>gnodes. Let's look at a couple of examples.To add a new node, you simply read until the parent is found and then write an extraset of nodes to the <strong>XML</strong> writer. Because there might be other nodes with the samename as the parent, use a Boolean guard to ensure that the <strong>in</strong>sertion takes place onlyonce. The follow<strong>in</strong>g code demonstrates how to proceed:void AddUser(str<strong>in</strong>g name, str<strong>in</strong>g pswd, str<strong>in</strong>g role){XmlTextReadWriter rw;rw = new XmlTextReadWriter(<strong>in</strong>putFile, outputFile);rw.WriteStartDocument();// Modify the root tag manuallyrw.Writer.WriteStartElement(rw.Reader.LocalName);// Loop through the documentbool mustAddNode = true; // Only oncewhile(rw.Read()){switch(rw.NodeType){case XmlNodeType.Element:rw.Writer.WriteStartElement(rw.Reader.LocalName);if ("Users" == rw.Reader.LocalName && mustAddNode)158

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

Saved successfully!

Ooh no, something went wrong!