December 2007
Intermediate to advanced
896 pages
19h 57m
English
Given a URL that points to an XML document, you need to grab the XML.
Use the XDocument constructor that takes a URL as a parameter:
// This requires you set up a virtual directory pointing
// to the sample.xml file included with the sample code
// prior to executing this.
string url = "http://localhost/xml/sample.xml";
XDocument xDoc = XDocument.Load(url);
var query = from e in xDoc.Descendants( )
where e.NodeType == XmlNodeType.Element
select new
{
ElementName = e.Name.ToString( ),
ElementValue = e.Value
};
foreach(var elementInfo in query)
{
Console.WriteLine("Element Name: {0}, Value: {1}",
elementInfo.ElementName,elementInfo.ElementValue);
}Or if you don't want to use LINQ for XML, use the XmlReader constructor that takes a URI 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("\r\nElement Name: {0}, Value: ",
reader.Name);
break;
case XmlNodeType.Text:
Console.Write(reader.Value);
break;
case XmlNodeType.CDATA:
Console.Write(reader.Value);
break;
}
}
}By using the Load method on XDocument or XElement, you can quickly load an XML document from the Web and then query it for a set of elements using LINQ. Once the set of elements is returned, a simple foreach loop allows access to the individual elements.
Retrieving XML and examining all of the elements can also be achieved ...
Read now
Unlock full access