有一段xml格式的字符串:
string xmlStr= @" <?xml version='1.0' encoding='UTF-8'?>
<result status='ok'>
<order id='5322' policyId='100' orderNo='abc' contactMob='13012313'>
<passenger name='王五' cardNum='12******31'></passenger>
<passenger name='赵六' cardNum='12******32'></passenger>
</order>
<order id='5323' policyId='100' orderNo='def' contactMob='13012314'>
<passenger name='张一' cardNum='12******31'></passenger>
<passenger name='李二' cardNum='12******32'></passenger>
</order>
<order id='5324' policyId='200' orderNo='ghi' contactMob='13012315'>
<passenger name='钱三' cardNum='12******31'></passenger>
<passenger name='孙四' cardNum='12******32'></passenger>
</order>
</result>";
现要求查询出policyId=100的passger相关信息,以orderNo/name/contactMob/cardNum格式输出,
传统的解析方式:
XmlDocument xd = new XmlDocument();
xd.LoadXml(url);
if (!Equals(xd.SelectNodes("result")[0], null) && xd.SelectNodes("result")[0].Attributes["status"].Value == "ok")
{
XmlNodeList list = xd.DocumentElement.SelectNodes("//order[@policyId='100']");//得到订单中policyId字段为100的所有order节点
foreach (XmlElement xe in list)
{
foreach (XmlElement xet in xe.GetElementsByTagName("passenger")) //得到order中的所有passenger节点
{
serverOrderMessage += xe.Attributes["orderNo"].Value;
serverOrderMessage += "/";
serverOrderMessage += xet.Attributes["name"].Value;
serverOrderMessage += "/";
serverOrderMessage += xe.Attributes["contactMob"].Value;
serverOrderMessage += "/";
serverOrderMessage += xet.Attributes["cardNum"].Value;
Response.Write("<script> alert('" + serverOrderMessage.ToString() + "')</script>");
}
}
}
用 linq to xml 解析:
//XDocument xd = XDocument.Parse(url);
XElement xmlPage = XElement.Parse(url);
string serverOrderMessage = string.Empty;
if (!Equals(xmlPage, null) && xmlPage.Attribute("status").Value == "ok")
{
var orders = from o in xmlPage.Descendants("order")
where o.Attribute("policyId").Value.Equals("100")
select o; //得到订单中policyId字段为100的所有order节点
foreach (var order in orders)
{
var passengers = from p in order.Descendants("passenger") //得到order中的所有passenger节点
select p;
foreach(var passenger in passengers)
{
serverOrderMessage += order.Attribute("orderNo").Value;
serverOrderMessage += "/";
serverOrderMessage += passenger.Attribute("name").Value;
serverOrderMessage += "/";
serverOrderMessage += order.Attribute("contactMob").Value;
serverOrderMessage += "/";
serverOrderMessage += passenger.Attribute("cardNum").Value;
Response.Write("<script> alert('" + serverOrderMessage.ToString() + "')</script>");
}
}
}
XDocument和XElement对象都通过Parse方法来加载xml格式的字符串,通过load方法加载xml文档,关于两者的区别,参看msdn:
http://msdn.microsoft.com/zh-cn/library/bb675196%28v=vs.90%29.aspx