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.

Str<strong>in</strong>gBuilder sb = new Str<strong>in</strong>gBuilder("");<strong>for</strong>each(XmlNode n <strong>in</strong> nodes)sb.Append(n.OuterXml);sb.Append("");return sb.ToStr<strong>in</strong>g();Our sample application <strong>in</strong>tentionally follows a more sophisticated approach to display<strong>for</strong>matted output <strong>in</strong> the text box. In addition, this code turns out to be a useful exercise<strong>for</strong> understand<strong>in</strong>g the logic of <strong>XML</strong> writers.If you want to generate <strong>XML</strong> output <strong>in</strong> the .<strong>NET</strong> Framework, unless the text is short andstraight<strong>for</strong>ward, you have no good reason <strong>for</strong> not us<strong>in</strong>g <strong>XML</strong> writers. Us<strong>in</strong>g <strong>XML</strong> writersalso provides automatic and free <strong>in</strong>dentation. Don't th<strong>in</strong>k that choos<strong>in</strong>g an <strong>XML</strong> writerties you to us<strong>in</strong>g a specific output stream. As the follow<strong>in</strong>g code demonstrates, theoutput of an <strong>XML</strong> writer can be easily redirected to a str<strong>in</strong>g:str<strong>in</strong>g BuildOutputStr<strong>in</strong>g(XmlNodeList nodes){// Create a str<strong>in</strong>g writer to hold the <strong>XML</strong> text. Forefficiency,// the str<strong>in</strong>g writer is based on a Str<strong>in</strong>gBuilder object.Str<strong>in</strong>gBuilder sb = new Str<strong>in</strong>gBuilder("");Str<strong>in</strong>gWriter sw = new Str<strong>in</strong>gWriter(sb);// Instantiate the <strong>XML</strong> writerXmlTextWriter writer = new XmlTextWriter(sw);writer.Formatt<strong>in</strong>g = Formatt<strong>in</strong>g.Indented;// Write the first element (No WriteStartDocument call isneeded)writer.WriteStartElement("results");// Loop through the children of each selected node and// recursively output attributes and text<strong>for</strong>each(XmlNode n <strong>in</strong> nodes)LoopThroughChildren(writer, n);// Complete pend<strong>in</strong>g nodes and then close the writerwriter.WriteEndElement();writer.Close();}// Flush the contents accumulated <strong>in</strong> the str<strong>in</strong>g writerreturn sw.ToStr<strong>in</strong>g();Let's see what happens when we process the follow<strong>in</strong>g <strong>XML</strong> document:212

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

Saved successfully!

Ooh no, something went wrong!