03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

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.

Reading XML Data ❘ 549<br />

Method<br />

Read<br />

ReadInnerXml<br />

ReadOuterXml<br />

ReadToDescendant<br />

ReadToNextSibling<br />

Skip<br />

Purpose<br />

Reads the next node from the XML data.<br />

Returns the current node’s descendants as an XML string.<br />

Returns the current node’s subtree (including the current node) as<br />

an XML string.<br />

Moves the reader to a subelement with a specified name.<br />

Moves the reader past the rest of the current node to its<br />

next sibling.<br />

Skips the current node’s children.<br />

The ReadXml example program, which is available for download on this book’s website, uses the<br />

following code to read an XML file.<br />

// Read the XML data.<br />

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

{<br />

string result = "";<br />

// Open a reader for the XML file.<br />

using (XmlReader reader = XmlReader.Create(fileTextBox.Text))<br />

{<br />

// Read tags from the file.<br />

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

{<br />

switch (reader.NodeType)<br />

{<br />

case XmlNodeType.Element:<br />

result += "Element: " + reader.Name + "\r\n";<br />

if (reader.HasAttributes)<br />

{<br />

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

result += " Attribute: " + reader[i] + "\r\n";<br />

}<br />

break;<br />

case XmlNodeType.EndElement:<br />

result += "EndElement: " + reader.Name + "\r\n";<br />

break;<br />

case XmlNodeType.Text:<br />

result += "Text: " + reader.Value + "\r\n";<br />

break;<br />

case XmlNodeType.CDATA:<br />

result += "CDATA: [" +<br />

reader.Value.Replace("\n","\r\n") + "]\r\n";<br />

break;<br />

case XmlNodeType.Comment:<br />

result += "Comment: " + reader.Value + "\r\n";<br />

break;<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!