Skip to main content
 首页 » 编程设计

c#之解析URL/Web服务

2024年01月22日28qq号

我向第三方API发出了请求,它以XML给出了以下响应。

<?xml version="1.0" ?> 
<abc> 
<xyz> 
<code>-112</code> 
<message>No such device</message> 
</xyz> 
</abc> 


我使用此代码阅读。

 XmlDocument doc = new XmlDocument(); 
    doc.Load("*** url ***"); 
 
    XmlNode node = doc.SelectSingleNode("/abc/xyz"); 
    string code = node.SelectSingleNode("code").InnerText; 
    string msg = node.SelectSingleNode("message").InnerText; 
 
    Response.Write("Code: " + code); 
Response.Write("Message: "+ msg); 


但是我在这条线上出现错误:

string code = node.SelectSingleNode("code").InnerText; 


错误是:


  你调用的对象是空的。

请您参考如下方法:

我将XML文件的第一行更改为:

<?xml version="1.0"?> 


使其成为有效的XML。进行此更改后,您的代码对我有用。没有更改,解析器将引发异常。