快速读取xml节点内容

XML内容如下:
View Code
 1 <promotion_coupons_get_response>
2 <tot_results>
3 200
4 </tot_results>
5 <coupons list="true">
6 <coupon>
7 <coupon_id>
8 123456
9 </coupon_id>
10 <denominations>
11 5
12 </denominations>
13 <creat_time>
14 2000-01-01 00:00:00
15 </creat_time>
16 <end_time>
17 2000-01-01 00:00:00
18 </end_time>
19 <condition>
20 500
21 </condition>
22 </coupon>
23 </coupons>
24 </promotion_coupons_get_response>

加载这个xml文件:

XMLDocument xmlDoc = new XmlDocument();

然后可以通过xmlDoc .Load(...)或xmlDoc.LoadXml(...)方法加载XML文档。

加载完这个xml文档后,我们可以通过下面的方法快速读取节点内的内容。

快速获取xml节点内容的方法为:

View Code
 1 /// <summary>
2 /// 获取XML结点值
3 /// </summary>
4 /// <param name="Str">xml,如:XmlNodeList[0].InnerXml</param>
5 /// <param name="xPath">结点,如:time这个结点</param>
6 /// <returns></returns>
7 public static string get_Str_Nodes(string Str, string xPath)
8 {
9 int x = 0, y = 0, z = 0;
10 x = Str.IndexOf("<" + xPath + ">");
11 y = Str.IndexOf("</" + xPath + ">");
12 z = xPath.Length + 2;
13 if (y > x)
14 {
15 return Str.Substring(x + z, y - x - z).Trim();
16 }
17 else
18 {
19 return "";
20 }
21 }

上面的方法不再做解释,具体运用例子如下:

View Code
 1 XmlNodeList couponNodes = CouponXml.SelectNodes("//coupon"); 
2
3 if (couponNodes != null)
4 {
5 foreach(XmlNode couponNode in couponNodes)
6 {
7 string coupon_Id = get_Str_Nodes(couponNode.InnerXml, "coupon_Id");
8 string denominations = get_Str_Nodes(couponNode.InnerXml, "denominations");
9 }
10 }

可以把获取节点值的方法放在共通类里面,已经经过测试了。

-------------------------------------------------------------仅供学习交流 转载请注明出处----------------------------------------------------------------


 

原文地址:https://www.cnblogs.com/willpan/p/xml.html