15.02.2015 Views

C# 4 and .NET 4

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

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

eading <strong>and</strong> Writing streamed XMl ❘ 909<br />

private void button5_Click(object sender, EventArgs e)<br />

{<br />

richTextBox1.Clear();<br />

XmlReader rdr = XmlReader.Create("books.xml");<br />

while (rdr.Read())<br />

{<br />

if (rdr.NodeType == XmlNodeType.Element)<br />

{<br />

if (rdr.Name == "price")<br />

{<br />

decimal price = rdr.ReadElementContentAsDecimal();<br />

richTextBox1.AppendText("Current Price = " + price + "\r\n");<br />

price += price * (decimal).25;<br />

richTextBox1.AppendText("New Price = " + price + "\r\n\r\n");<br />

}<br />

else if(rdr.Name== "title")<br />

richTextBox1.AppendText(rdr.ReadElementContentAsString() + "\r\n");<br />

}<br />

}<br />

}<br />

code download XMLReaderSample.sln<br />

If the value cannot be converted to a decimal value, a FormatException is raised. This is a much more<br />

efficient method than reading the value as a string <strong>and</strong> casting it to the proper data type.<br />

retrieving attribute Data<br />

As you play with the sample code, you might notice that when the nodes are read in, you don’t see<br />

any attributes. This is because attributes are not considered part of a document’s structure. When<br />

you are on an element node, you can check for the existence of attributes <strong>and</strong> optionally retrieve the<br />

attribute values.<br />

For example, the HasAttributes property returns true if there are any attributes; otherwise, it returns<br />

false. The AttributeCount property tells you how many attributes there are, <strong>and</strong> the GetAttribute()<br />

method gets an attribute by name or by index. If you want to iterate through the attributes one at a time,<br />

you can use the MoveToFirstAttribute() <strong>and</strong> MoveToNextAttribute() methods.<br />

The following is an example of iterating through the attributes of the books.xml document:<br />

private void button7_Click(object sender, EventArgs e)<br />

{<br />

richTextBox1.Clear();<br />

XmlReader tr = XmlReader.Create("books.xml");<br />

//Read in node at a time<br />

while (tr.Read())<br />

{<br />

//check to see if it's a NodeType element<br />

if (tr.NodeType == XmlNodeType.Element)<br />

{<br />

//if it's an element, then let's look at the attributes.<br />

for (int i = 0; i < tr.AttributeCount; i++)<br />

{<br />

richTextBox1.AppendText(tr.GetAttribute(i) + "\r\n");<br />

}<br />

}<br />

}<br />

}<br />

code download XMLReaderSample.sln<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!