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.

Other controls that the XmlTextWriter class per<strong>for</strong>ms on the generated <strong>XML</strong> outputensure that each document starts with the standard <strong>XML</strong> prolog, shown <strong>in</strong> the follow<strong>in</strong>gcode, and that any DOCTYPE node always precedes the document root node:This said, there is no absolute guarantee that users won't write badly <strong>for</strong>med code. Ifthe bad <strong>for</strong>mat can be detected, the writer throws an exception. Otherwise, the file isconsidered correctly written, but client applications might compla<strong>in</strong> about it, as <strong>in</strong> Figure4-2.Figure 4-2: An <strong>XML</strong> file created with the XmlTextWriter class has a duplicated attribute thatthe class did not discover.The follow<strong>in</strong>g code demonstrates how to write two identical attributes <strong>for</strong> a specifiednode:xmlw.WriteStartElement("element");xmlw.WriteAttributeStr<strong>in</strong>g("value", s);xmlw.WriteAttributeStr<strong>in</strong>g("value", s);xmlw.WriteEndElement();In the check made just be<strong>for</strong>e dump<strong>in</strong>g data out, the writer neither verifies the namesand semantics of the attributes nor validates the schema of the resultant document,thus authoriz<strong>in</strong>g this code to generate bad <strong>XML</strong>.Build<strong>in</strong>g an <strong>XML</strong> DocumentUp to now, we've looked at several code snippets show<strong>in</strong>g the <strong>XML</strong> text writer <strong>in</strong> action,but without go<strong>in</strong>g <strong>in</strong>to details. Let's make up <strong>for</strong> this now. The necessary steps to createan <strong>XML</strong> document can be summarized as follows:• Initialize the document The output stream is already open, and at thisstage you simply write the <strong>XML</strong> prolog, <strong>in</strong>clud<strong>in</strong>g the <strong>XML</strong> 1.0 defaultdeclaration and any other head<strong>in</strong>g <strong>in</strong><strong>for</strong>mation that the recommendationmandates to precede actual data nodes. (Typically, this <strong>in</strong><strong>for</strong>mationconsists of process<strong>in</strong>g <strong>in</strong>structions, schema references, and the DTD.)• Write data At this stage, you create <strong>XML</strong> nodes such as element nodes,attributes, CDATA and parsable text, entities, white space, and whatever121

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

Saved successfully!

Ooh no, something went wrong!