XmlNodeList students = doc.DocumentElement.ChildNodes;//Student节点集合 foreach (XmlNode stu in students) { XmlElement element = (XmlElement)stu; string stuId = element.GetAttribute("StuID"); XmlNode nameNode = element.SelectSingleNode("StuName");//获取Person节点的Name节点 string name = nameNode.InnerText; Console.WriteLine(stuId + "," + name); }
案例xml文件
又一个解析xml文件的方法:
public static void WriteTOXmlStatusLog(string responseStr)
{ string pathConfig = App.GetSetting("TracePath");
if (!string.IsNullOrWhiteSpace(pathConfig))
{
try
{
Log4NetTraceListener log = new Log4NetTraceListener(pathConfig + @"\UserInterface");
var doc = new System.Xml.XmlDocument();
doc.LoadXml(responseStr);
string error = "";
var errorNode = doc.SelectSingleNode("/returnsms/errorstatus/error");
if (errorNode != null)
{
error = errorNode.InnerText;
}
if (string.IsNullOrWhiteSpace(error))
{
XmlNodeList callboxList = doc.DocumentElement.ChildNodes;
foreach (XmlNode item in callboxList)
{
XmlElement element = (XmlElement)item;
string mobile= element.GetElementsByTagName("mobile")[].InnerText;
//string mobile = element.SelectSingleNode("/statusbox/mobile").InnerText;
string taskid = element.GetElementsByTagName("taskid")[].InnerText;
string status = element.GetElementsByTagName("status")[].InnerText;
string receivetime = element.GetElementsByTagName("receivetime")[].InnerText;
string extno = element.GetElementsByTagName("extno")[].InnerText;
string errorcode = element.GetElementsByTagName("errorcode")[].InnerText;
log.WriteLine("获取状态报告返回xml信息:" + "mobile:" + mobile + ",taskid:" + taskid + ",status:" + status + ",receivetime:" + receivetime + ",errorcode:" + errorcode + ",extno:" + extno);
} }
else
{
string remark = doc.SelectSingleNode("/returnsms/errorstatus/remark").InnerText;
log.WriteLine("获取状态报告返回xml信息:error:" + error + ",remark:" + remark);
} }
catch (Exception ex)
{ throw new Exception("获取xml状态报告信息写入日志出错:" + ex);
}
}
xml文件:
//错误时的返回
<?xml version="1.0" encoding="utf-8" ?>
<returnsms>
<errorstatus>
<error></error>-------------错误码
<remark>用户名或密码不能为空</remark>-------------错误描述
</errorstatus>
</returnsms> //正确时的返回
<?xml version="1.0" encoding="utf-8" ?>
<returnsms>
<statusbox>
<mobile></mobile>-------------对应的手机号码
<taskid></taskid>-------------同一批任务ID
<status></status>---------状态报告----:发送成功,:发送失败
<receivetime>-- ::</receivetime>-------------接收时间
<errorcode>DELIVRD</errorcode>-上级网关返回值,不同网关返回值不同,仅作为参考
<extno></extno>--子号,即自定义扩展号
</statusbox>
<statusbox>
<mobile></mobile>
<taskid></taskid>
<status></status>
<receivetime>-- ::</receivetime>
<errorcode></errorcode>
<extno></extno>