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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

}sw.Write(sb.ToStr<strong>in</strong>g());sw.Close();The output is shown <strong>in</strong> Figure 4-1. Apparently, everyth<strong>in</strong>g is work<strong>in</strong>g just f<strong>in</strong>e.Figure 4-1: The sample <strong>XML</strong> file is successfully recognized and managed by <strong>Microsoft</strong>Internet Explorer.One small drawback is that the <strong>XML</strong> code you get is not exactly <strong>in</strong> the <strong>for</strong>mat youexpect—the <strong>for</strong>mat shown <strong>in</strong> Internet Explorer. The source code <strong>for</strong> the <strong>XML</strong> file <strong>in</strong>Figure 4-1 has no newl<strong>in</strong>e characters or <strong>in</strong>dentation and appears to be an endless andhardly readable str<strong>in</strong>g of markup text. But this is no big deal. You can simply enhancethe code a little bit by add<strong>in</strong>g newl<strong>in</strong>e and tab characters.In general, there is noth<strong>in</strong>g really bad or wrong with this approach as long as thedocument file you need to create is simple, has m<strong>in</strong>imal structure, and has only a fewlevels of nest<strong>in</strong>g. When you have more advanced and stricter requirements such asprocess<strong>in</strong>g <strong>in</strong>structions, namespaces, <strong>in</strong>dentation, <strong>for</strong>matt<strong>in</strong>g, and entities, thecomplexity of your code can grow exponentially and, with it, the likelihood of <strong>in</strong>troduc<strong>in</strong>gerrors and bugs.Let's rewrite our sample file us<strong>in</strong>g .<strong>NET</strong> <strong>XML</strong> writers, as shown <strong>in</strong> the follow<strong>in</strong>g code. A.<strong>NET</strong> <strong>XML</strong> writer features ad hoc write methods <strong>for</strong> each possible <strong>XML</strong> node type andmakes the creation of <strong>XML</strong> output more logical and much less dependent on the<strong>in</strong>tricacies, and even the quirk<strong>in</strong>ess, of the markup languages.void CreateXmlFileUs<strong>in</strong>gWriters(Str<strong>in</strong>g[] theArray,str<strong>in</strong>g filename){// Open the <strong>XML</strong> writer (default encod<strong>in</strong>g charset)XmlTextWriter xmlw = new XmlTextWriter(filename, null);xmlw.Formatt<strong>in</strong>g = Formatt<strong>in</strong>g.Indented;xmlw.WriteStartDocument();xmlw.WriteStartElement("array");<strong>for</strong>each(str<strong>in</strong>g s <strong>in</strong> theArray)112

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

Saved successfully!

Ooh no, something went wrong!