Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

17.2. Reading XML on the Web

Problem

Given a URL that points to an XML document, you need to grab the XML.

Solution

Use the XmlTextReader constructor that takes a URL as a parameter:

string url = "http://localhost/xml/sample.xml";

// use the XmlTextReader to get the xml at the url
XmlTextReader reader = new XmlTextReader (url);

    while (reader.Read( ))
    {
        switch (reader.NodeType) 
        {
            case XmlNodeType.Element :
                Console.Write("<{0}>", reader.Name);
                break;
        }       
    }
    reader

Discussion

The sample.xml file being referenced in this code is set up in a virtual directory named xml on the local system. The code retrieves the sample.xml file from the web server and displays all of the elements in the XML.

Sample.xml contains the following XML data:

<?xml version='1.0'?>
<!-- My sample XML -->
<?pi myProcessingInstruction?>
<Root>
    <Node1 nodeId='1'>First Node</Node1>
    <Node2 nodeId='2'>Second Node</Node2>
    <Node3 nodeId='3'>Third Node</Node3>
    <Node4><![CDATA[<>\&']]></Node4>
</Root>

See Also

See the “XmlTextReader Class” topic in the MSDN documentation.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata