Reading XML on the Web

Reading XML on the Web


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


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

	string url = "http://localhost/xml/sample.xml";
	using (XmlReader reader = XmlReader.Create(url))
	    while (reader.Read())
	        switch (reader.NodeType)
	            case XmlNodeType.Element:
	                Console.Write("<{0}>", reader.Name);


Using the XmlReader.Create method with a URI is a quick way to access XML documents that are stored remotely without writing all of the connectivity code. This uses an instance of the XmlUrlResolver class to check the URI passed in and then opens a stream to the XML document indicated by the URI. To specify settings on the reader, there is a second overload of Create that also takes an XmlReaderSettings instance to facilitate this.

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?>
	    <Node1 nodeId='1'>First Node</Node1>
	    <Node2 nodeId='2'>Second Node</Node2>
	    <Node3 nodeId='3'>Third Node</Node3>

See Also

See the "XmlReader Class" topic in the MSDN documentation.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows