温馨提示:代码在线浏览功能只能做为源码浏览参考,不能展示项目的全部,如果想更进一步了解该代码请下载:简单的XML学生信息系统(注释清楚)
当前文件路径:XmlStudentSys/App_Code/XmlOp.cs

1using System; 2
using System.Data; 3
using System.Configuration; 4
using System.Web; 5
using System.Web.Security; 6
using System.Web.UI; 7
using System.Web.UI.WebControls; 8
using System.Web.UI.WebControls.WebParts; 9
using System.Web.UI.HtmlControls; 10
using System.IO; 11
//引用命名空间 12
using System.Xml; 13
//51aspx.c_o_m 14
15
namespace xmlOp 16
{ 17
/// <summary> 18
/// xmlOp 类提供对XML文件的读/写/查询/更新/添加/删除 等操作! 19
/// </summary> 20
public class XmlOp 21
{ 22
//声明一个XmlDocument空对象 23
protected XmlDocument doc = new XmlDocument(); 24
public XmlOp(string xmlFile) 25
{ 26
doc.Load(GetXmlFilePath(xmlFile));//载入Xml文档 27
} 28
//保存文件 29
public void Save(string filePath) 30
{ 31
doc.Save(GetXmlFilePath(filePath)); 32
} 33
//属性查询,返回属性值 34
public string SelectAttrib(string XmlPathNode, string Attrib) 35
{ 36
string _strNode = ""; 37
_strNode = doc.SelectSingleNode(XmlPathNode).Attributes[Attrib].Value; 38
return _strNode; 39
} 40
// 添加属性 41
public bool InsertAttrib(string MainNode, string Attrib, string AttribContent) 42
{ 43
try 44
{ 45
XmlElement objNode = (XmlElement)doc.SelectSingleNode(MainNode); //强制转化成XmlElement对象 46
objNode.SetAttribute(Attrib, AttribContent); //XmlElement对象添加属性方法 47
return true; 48
} 49
catch 50
{ 51
return false; 52
} 53
} 54
//节点值查询与判断 55
public bool SelectNode(string XmlPathNode, int index, string NodeText) 56
{ 57
XmlNodeList _NodeList = doc.SelectNodes(XmlPathNode); 58
//循环遍历节点,查询是否存在该节点 59
for (int i = 0; i < _NodeList.Count; i++) 60
{ 61
if (_NodeList[i].ChildNodes[index].InnerText == NodeText) 62
{ 63
return true; 64
break; 65
} 66
} 67
return false; 68
} 69
//获取子节点个数 70
public int NodeCount(string XmlPathNode) 71
{ 72
int i = 0; 73
try 74
{ 75
i = doc.SelectSingleNode(XmlPathNode).ChildNodes.Count; 76
} 77
catch 78
{ 79
i = 0; 80
} 81
return i; 82
} 83
//插入一个节点,带N个子节点 84
public bool InsertNode(string MainNode, string ChildNode, string[] Element, string[] Content) 85
{ 86
try 87
{ 88
XmlNode objRootNode = doc.SelectSingleNode(MainNode); //声明XmlNode对象 89
XmlElement objChildNode = doc.CreateElement(ChildNode); //创建XmlElement对象 90
objRootNode.AppendChild(objChildNode); 91
for (int i = 0; i < Element.Length; i++) //循环插入节点元素 92
{ 93
XmlElement objElement = doc.CreateElement(Element[i]); 94
objElement.InnerText = Content[i]; 95
objChildNode.AppendChild(objElement); 96
} 97
return true; 98
} 99
catch 100
{ 101
return false; 102
} 103
} 104
// 根据Xml文件的节点路径,返回一个DataSet数据集 105
public DataSet GetDs(string XmlPathNode) 106
{ 107
DataSet ds = new DataSet(); 108
try 109
{ 110
StringReader read = new StringReader(doc.SelectSingleNode(XmlPathNode).OuterXml); 111
ds.ReadXml(read); //利用DataSet的ReadXml方法读取StringReader文件流 112
read.Close(); 113
} 114
catch 115
{ } 116
return ds; 117
} 118
// 返回Xml文件实际路径 119
public string GetXmlFilePath(string xmlFile) 120
{ 121
return xmlFile; 122
} 123
} 124
} 125
126





}