DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 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.

    [ Team LiB ] Previous Section Next Section