First, use LINQ to read
Using the Load method on XDocument, you can quickly load an XML document and then use LINQ to query or otherwise load an XML document, which is only a simple partial calendar. So once a group of elements is queried for a set of returned elements, a simple foreach loop can be used to iterate through each element. The core code is as follows:
/// <summary>
/// 使用LINQ读取web上的xml
/// </summary>
public static void UseLINQ()
{
string sURL = "http://localhost:9058/GameServerInfo/XMLFile.xml";
XDocument oXDoc = XDocument.Load(sURL);
var qurey = from e in oXDoc.Descendants()
where e.NodeType == XmlNodeType.Element
select new
{
ElementName=e.Name.ToString(),
ElementValue=e.Value
};
foreach(var elementInfo in qurey)
{
HttpContext.Current.Response.Write(string.Format("ElementName->{0} ElementValue->{1}<br />", elementInfo.ElementName, elementInfo.ElementValue));
}
}
Second, using the XmlReader constructor
Of course, you can do this by using the Xmlreader.create method with a URL, which uses an instance of a XmlUrlResolver class to detect the incoming URL and then open a stream of XML documents that is represented by the URL. To specify settings on the reader, you can use another create overload, which is also done with a xmlreadersetting instance. The code is as follows:
<summary>
Using the XmlReader constructor
</summary>
public static void Usexmlreader ()
{
String surl = "Http://localhost:9058/GameServerInfo/XMLFile.xml";
using (XmlReader read=xmlreader.create (sURL))
{
while (read. Read ())
{
Switch (read. NodeType)
{
Case XmlNodeType.Element:
HttpContext.Current.Response.Write (String. Format ("elementname->{0} <br/>", read. Name));
Break
Case XmlNodeType.Text:
HttpContext.Current.Response.Write (String. Format ("elementvalue->{0}<br/>", read. Value));
Break
Case Xmlnodetype.cdata:
HttpContext.Current.Response.Write (String. Format ("elementvalue->{0}<br/>", read. Value));
Break
Other
}
}
}
}
This article supporting source code