关于XML文档操作类
生活随笔
收集整理的這篇文章主要介紹了
关于XML文档操作类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Xml;
6
7 namespace ZW.ClassLibrary
8 {
9 public class XmlHelpers
10 {
11 /// <summary>
12 /// XML文檔
13 /// </summary>
14 XmlDocument xd = new XmlDocument();
15
16 /// <summary>
17 /// 從文件中獲取XmlDocument對象
18 /// </summary>
19 /// <param name="file">xml文檔</param>
20 /// <param name="type">文檔類型</param>
21 public XmlHelpers(string file, string type)
22 {
23 if (type == "path")
24 {
25 XmlTextReader xr = new XmlTextReader(file);
26 xd.Load(xr);
27 xr.Close();
28 }
29
30 if (type == "text")
31 {
32 xd.LoadXml(file);
33 }
34 }
35
36 /// <summary>
37 /// 獲取第一個匹配節點的屬性值
38 /// </summary>
39 /// <param name="nodePath"></param>
40 /// <param name="attrName"></param>
41 /// <returns></returns>
42 public string GetAttribute(string nodePath, string attrName)
43 {
44 XmlNode xn = xd.SelectSingleNode(nodePath);
45 if (xn == null) //檢測節點是否存在
46 {
47 return "";
48 }
49 if (xn.Attributes[attrName] == null) //檢測屬性是否存在
50 {
51 return "";
52 }
53
54 return xn.Attributes[attrName].Value;
55 }
56
57 /// <summary>
58 /// 獲取某個節點
59 /// </summary>
60 /// <param name="nodePath"></param>
61 /// <returns></returns>
62 public XmlNode GetNode(string nodePath)
63 {
64 XmlNode xn = xd.SelectSingleNode(nodePath);
65 return xn;
66 }
67
68 /// <summary>
69 /// 獲取某個節點子集合指定屬性值的節點
70 /// </summary>
71 /// <param name="nodePath">父節點</param>
72 /// <returns></returns>
73 public XmlNode GetNode(string nodePath, string attrName, string attrValue)
74 {
75 XmlNodeList xl = GetChildNode(nodePath);
76 if (xl != null)
77 {
78 foreach (XmlNode node in xl)
79 {
80 if (node.Attributes[attrName] != null) //檢測屬性是否存在
81 {
82 if (node.Attributes[attrName].Value.Trim() == attrValue)
83 {
84 return node;
85 }
86 }
87 }
88 }
89 return null;
90 }
91
92 /// <summary>
93 /// 獲取某個節點上的子節點
94 /// </summary>
95 /// <param name="nodePath"></param>
96 /// <returns></returns>
97 public XmlNodeList GetChildNode(string nodePath)
98 {
99 XmlNodeList xl = null;
100 XmlNode xn = xd.SelectSingleNode(nodePath);
101 if (xl != null)
102 {
103 xl = xd.ChildNodes;
104 }
105 return xl;
106 }
107 }
108 } View Code
?
轉載于:https://www.cnblogs.com/acpe/p/4499302.html
總結
以上是生活随笔為你收集整理的关于XML文档操作类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQLSERVER2014的内存优化表
- 下一篇: Nano PC ubuntu13.10