Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从XML而不是JSON C#asp.net读取_C#_Asp.net_Json_Xml - Fatal编程技术网

从XML而不是JSON C#asp.net读取

从XML而不是JSON C#asp.net读取,c#,asp.net,json,xml,C#,Asp.net,Json,Xml,嗨 今天,我有一个从URL检索JSON数据的代码。它工作得很好 但是现在我想做同样的事情,但是我想从XML而不是JSON中检索 我怎样才能做到最好 提前感谢, Json URL: XML URL: 公共类数据 { 公共列表名称{get;set;} } 公共类对象 { 公共字符串名{get;set;} 公共字符串姓氏{get;set;} } 受保护的无效页面加载(对象发送方、事件参数e) { WebClient客户端=新的WebClient(); string json=client.Downl

今天,我有一个从URL检索JSON数据的代码。它工作得很好

但是现在我想做同样的事情,但是我想从XML而不是JSON中检索

我怎样才能做到最好

提前感谢,

Json URL:
XML URL:

公共类数据
{
公共列表名称{get;set;}
}
公共类对象
{
公共字符串名{get;set;}
公共字符串姓氏{get;set;}
}
受保护的无效页面加载(对象发送方、事件参数e)
{
WebClient客户端=新的WebClient();
string json=client.DownloadString(“http://api.namnapi.se/v2/names.json?limit=3");
数据结果=new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(json);
foreach(result.names中的变量项)
{
Label.Text+=(item.firstname+“”+item.姓氏+“
”); } }
有几种方法可以在C#中解析XML

例如,您可以使用
XmlDocument

WebClient client = new WebClient();
string xml = client.DownloadString("http://api.namnapi.se/v2/names.xml?limit=3");

XmlDocument document = new XmlDocument();
document.LoadXml(xml);

foreach (XmlElement node in document.SelectNodes("names/name"))
{
    Label.Text += String.Format("{0} {1}<br/>", 
        node.SelectSingleNode("firstname").InnerText,  
        node.SelectSingleNode("lastname"));
}
WebClient=newWebClient();
string xml=client.DownloadString(“http://api.namnapi.se/v2/names.xml?limit=3");
XmlDocument document=新的XmlDocument();
LoadXml(xml);
foreach(文档中的XmlElement节点。选择节点(“名称/名称”))
{
Label.Text+=String.Format(“{0}{1}
”, node.SelectSingleNode(“firstname”).InnerText, node.SelectSingleNode(“lastname”); }
还有一些方法,如使用
XmlSerializer
将XML序列化到您自己的类中,
XmlTextReader
Linq2Xml
等。选择最合适的方法

阅读有关C#中XML解析的更多信息:


在Stackoverflow和其他互联网资源中有很多关于这个主题的信息

另外,在我看来,最好使用JSON,因为它可以节省多达GB的网络流量。

使用XmlSerializer类
WebClient client = new WebClient();
string xml = client.DownloadString("http://api.namnapi.se/v2/names.xml?limit=3");

XmlDocument document = new XmlDocument();
document.LoadXml(xml);

foreach (XmlElement node in document.SelectNodes("names/name"))
{
    Label.Text += String.Format("{0} {1}<br/>", 
        node.SelectSingleNode("firstname").InnerText,  
        node.SelectSingleNode("lastname"));
}