c# xml操作类
引子http://www.cnblogs.com/QDuck/archive/2007/01/10/617240.aspx
public class XmlControl
{
protected string strXmlFile;
protected XmlDocument objXmlDoc = new XmlDocument();
public XmlControl(string XmlFile)
{
//
// TODO: 在這裡加入建構函式的程式碼
//
try
{
objXmlDoc.Load(XmlFile);
}
catch (System.Exception ex)
{
throw ex;
}
strXmlFile = XmlFile;
}
public DataView GetData(string XmlPathNode)
{
//查找數據。返回一個DataView
DataSet ds = new DataSet();
StringReader read = new StringReader(objXmlDoc.SelectSingleNode(XmlPathNode).OuterXml);
ds.ReadXml(read);
return ds.Tables[0].DefaultView;
}
public void Replace(string XmlPathNode,string Content)
{
//更新節點內容。
objXmlDoc.SelectSingleNode(XmlPathNode).InnerText = Content;
}
public void Delete(string Node)
{
//刪除一個節點。
string mainNode = Node.Substring(0,Node.LastIndexOf("/"));
objXmlDoc.SelectSingleNode(mainNode).RemoveChild(objXmlDoc.SelectSingleNode(Node));
}
public void InsertNode(string MainNode,string ChildNode,string Element,string Content)
{
//插入一節點和此節點的一子節點。
XmlNode objRootNode = objXmlDoc.SelectSingleNode(MainNode);
XmlElement objChildNode = objXmlDoc.CreateElement(ChildNode);
objRootNode.AppendChild(objChildNode);
XmlElement objElement = objXmlDoc.CreateElement(Element);
objElement.InnerText = Content;
objChildNode.AppendChild(objElement);
}
public void InsertElement(string MainNode,string Element,string Attrib,string AttribContent,string Content)
{
//插入一個節點,帶一屬性。
XmlNode objNode = objXmlDoc.SelectSingleNode(MainNode);
XmlElement objElement = objXmlDoc.CreateElement(Element);
objElement.SetAttribute(Attrib,AttribContent);
objElement.InnerText = Content;
objNode.AppendChild(objElement);
}
public void InsertElement(string MainNode,string Element,string Content)
{
//插入一個節點,不帶屬性。
XmlNode objNode = objXmlDoc.SelectSingleNode(MainNode);
XmlElement objElement = objXmlDoc.CreateElement(Element);
objElement.InnerText = Content;
objNode.AppendChild(objElement);
}
public void Save()
{
//保存文檔。
try
{
objXmlDoc.Save(strXmlFile);
}
catch (System.Exception ex)
{
throw ex;
}
objXmlDoc = null;
}
}
=========================================================
实例应用:
string strXmlFile = Server.MapPath("TestXml.xml");
XmlControl xmlTool = new XmlControl(strXmlFile);
// 數據顯視
// dgList.DataSource = xmlTool.GetData("Book/Authors[ISBN=\"0002\"]");
// dgList.DataBind();
// 更新元素內容
// xmlTool.Replace("Book/Authors[ISBN=\"0002\"]/Content","ppppppp");
// xmlTool.Save();
// 添加一個新節點
// xmlTool.InsertNode("Book","Author","ISBN","0004");
// xmlTool.InsertElement("Book/Author[ISBN=\"0004\"]","Content","aaaaaaaaa");
// xmlTool.InsertElement("Book/Author[ISBN=\"0004\"]","Title","Sex","man","iiiiiiii");
// xmlTool.Save();
// 刪除一個指定節點的所有內容和屬性
// xmlTool.Delete("Book/Author[ISBN=\"0004\"]");
// xmlTool.Save();
// 刪除一個指定節點的子節點
// xmlTool.Delete("Book/Authors[ISBN=\"0003\"]");
// xmlTool.Save();
1<%
2Class XMLDOMDocument
3Private fNode,fANode
4Private fErrInfo,fFileName,fOpen
5Dim XmlDom
6
7'返回节点的缩进字串
8Private Property Get TabStr(byVal Node)
9TabStr=""
10If Node Is Nothing Then Exit Property
11If not Node.parentNode Is nothing Then TabStr=" "&TabStr(Node.parentNode)
12End Property
13
14'返回一个子节点对象,ElementOBJ为父节点,ChildNodeObj要查找的节点,IsAttributeNode指出是否为属性对象
15Public Property Get ChildNode(byVal ElementOBJ,byVal ChildNodeObj,byVal IsAttributeNode)
16Dim Element
17Set ChildNode=Nothing
18
19If IsNull(ChildNodeObj) Then
20If IsAttributeNode=false Then
21Set ChildNode=fNode
22Else
23Set ChildNode=fANode
24End If
25Exit Property
26ElseIf IsObject(ChildNodeObj) Then
27Set ChildNode=ChildNodeObj
28Exit Property
29End If
30
31Set Element=Nothing
32If LCase(TypeName(ChildNodeObj))="string" and Trim(ChildNodeObj)<>"" Then
33If IsNull(ElementOBJ) Then
34Set Element=fNode
35ElseIf LCase(TypeName(ElementOBJ))="string" Then
36If Trim(ElementOBJ)<>"" Then
37Set Element=XmlDom.selectSingleNode("//"&Trim(ElementOBJ))
38If Lcase(Element.nodeTypeString)="attribute" Then Set Element=Element.selectSingleNode("..")
39End If
40ElseIf IsObject(ElementOBJ) Then
41Set Element=ElementOBJ
42End If
43
44If Element Is Nothing Then
45Set ChildNode=XmlDom.selectSingleNode("//"&Trim(ChildNodeObj))
46ElseIf IsAttributeNode=true Then
47Set ChildNode=Element.selectSingleNode("./@"&Trim(ChildNodeObj))
48Else
49Set ChildNode=Element.selectSingleNode("./"&Trim(ChildNodeObj))
50End If
51End If
52End Property
53
54'读取最后的错误信息
55Public Property Get ErrInfo
56ErrInfo=fErrInfo
57End Property
58
59'给xml内容
60Public Property Get xmlText(byVal ElementOBJ)
61xmlText=""
62If fopen=false Then Exit Property
63
64Set ElementOBJ=ChildNode(XmlDom,ElementOBJ,false)
65If ElementOBJ Is Nothing Then Set ElementOBJ=XmlDom
66
67xmlText=ElementOBJ.xml
68End Property
69
70'=================================================================
71'类初始化
72Private Sub Class_Initialize()
73Set XmlDom=CreateObject("Microsoft.XMLDOM")
74XmlDom.preserveWhiteSpace=true
75
76Set fNode=Nothing
77Set fANode=Nothing
78
79fErrInfo=""
80fFileName=""
81fopen=false
82End Sub
83
84'类释放
85Private Sub Class_Terminate()
86Set fNode=Nothing
87Set fANode=Nothing
88Set XmlDom=nothing
89fopen=false
90End Sub
91
92'=====================================================================
93'建立一个XML文件,RootElementName:根结点名。XSLURL:使用XSL样式地址
94'返回根结点
95Function Create(byVal RootElementName,byVal XslUrl)
96Dim PINode,RootElement
97
98Set Create=Nothing
99
100If (XmlDom Is Nothing) Or (fopen=true) Then Exit Function
101
102If Trim(RootElementName)="" Then RootElementName="Root"
103
104Set PINode=XmlDom.CreateProcessingInstruction("xml", "version=""1.0"" encoding=""GB2312""")
105XmlDom.appendChild PINode
106
107Set PINode=XMLDOM.CreateProcessingInstruction("xml-stylesheet", "type=""text/xsl"" href="""&XslUrl&"""")
108XmlDom.appendChild PINode
109
110Set RootElement=XmlDom.createElement(Trim(RootElementName))
111XmlDom.appendChild RootElement
112
113Set Create=RootElement
114
115fopen=True
116set fNode=RootElement
117End Function
118
119'开打一个已经存在的XML文件,返回打开状态
120Function Open(byVal xmlSourceFile)
121Open=false
122
123xmlSourceFile=Trim(xmlSourceFile)
124If xmlSourceFile="" Then Exit Function
125
126XmlDom.async = false
127XmlDom.load xmlSourceFile
128
129fFileName=xmlSourceFile
130
131If not IsError Then
132Open=true
133fopen=true
134End If
135End Function
136
137'关闭
138Sub Close()
139Set fNode=Nothing
140Set fANode=Nothing
141
142fErrInfo=""
143fFileName=""
144fopen=false
145End Sub
146
147'读取一个NodeOBJ的节点Text的值
148'NodeOBJ可以是节点对象或节点名,为null就取当前默认fNode
149Function getNodeText(byVal NodeOBJ)
150getNodeText=""
151If fopen=false Then Exit Function
152
153Set NodeOBJ=ChildNode(null,NodeOBJ,false)
154If NodeOBJ Is Nothing Then Exit Function
155
156If Lcase(NodeOBJ.nodeTypeString)="element" Then
157set fNode=NodeOBJ
158Else
159set fANode=NodeOBJ
160End If
161getNodeText=NodeOBJ.text
162End function
163
164'插入在BefelementOBJ下面一个名为ElementName,Value为ElementText的子节点。
165'IsFirst:是否插在第一个位置;IsCDATA:说明节点的值是否属于CDATA类型
166'插入成功就返回新插入这个节点
167'BefelementOBJ可以是对象也可以是节点名,为null就取当前默认对象
168Function InsertElement(byVal BefelementOBJ,byVal ElementName,byVal ElementText,byVal IsFirst,byVal IsCDATA)
169Dim Element,TextSection,SpaceStr
170Set InsertElement=Nothing
171
172If not fopen Then Exit Function
173
174Set BefelementOBJ=ChildNode(XmlDom,BefelementOBJ,false)
175If BefelementOBJ Is Nothing Then Exit Function
176
177Set Element=XmlDom.CreateElement(Trim(ElementName))
178
179'SpaceStr=vbCrLf&TabStr(BefelementOBJ)
180'Set STabStr=XmlDom.CreateTextNode(SpaceStr)
181
182'If Len(SpaceStr)>2 Then SpaceStr=Left(SpaceStr,Len(SpaceStr)-2)
183'Set ETabStr=XmlDom.CreateTextNode(SpaceStr)
184
185If IsFirst=true Then
186'BefelementOBJ.InsertBefore ETabStr,BefelementOBJ.firstchild
187BefelementOBJ.InsertBefore Element,BefelementOBJ.firstchild
188'BefelementOBJ.InsertBefore STabStr,BefelementOBJ.firstchild
189Else
190'BefelementOBJ.appendChild STabStr
191BefelementOBJ.appendChild Element
192'BefelementOBJ.appendChild ETabStr
193End If
194
195If IsCDATA=true Then
196set TextSection=XmlDom.createCDATASection(ElementText)
197Element.appendChild TextSection
198ElseIf ElementText<>"" Then
199Element.Text=ElementText
200End If
201
202Set InsertElement=Element
203Set fNode=Element
204End Function
205
206'在ElementOBJ节点上插入或修改名为AttributeName,值为:AttributeText的属性
207'如果已经存在名为AttributeName的属性对象,就进行修改。
208'返回插入或修改属性的Node
209'ElementOBJ可以是Element对象或名,为null就取当前默认对象
210Function setAttributeNode(byVal ElementOBJ,byVal AttributeName,byVal AttributeText)
211Dim AttributeNode
212Set setAttributeNode=nothing
213
214If not fopen Then Exit Function
215
216Set ElementOBJ=ChildNode(XmlDom,ElementOBJ,false)
217If ElementOBJ Is Nothing Then Exit Function
218
219Set AttributeNode=ElementOBJ.attributes.getNamedItem(AttributeName)
220If AttributeNode Is nothing Then
221Set AttributeNode=XmlDom.CreateAttribute(AttributeName)
222ElementOBJ.setAttributeNode AttributeNode
223End If
224AttributeNode.text=AttributeText
225
226set fNode=ElementOBJ
227set fANode=AttributeNode
228Set setAttributeNode=AttributeNode
229End Function
230
231'修改ElementOBJ节点的Text值,并返回这个节点
232'ElementOBJ可以对象或对象名,为null就取当前默认对象
233Function UpdateNodeText(byVal ElementOBJ,byVal NewElementText,byVal IsCDATA)
234Dim TextSection
235
236set UpdateNodeText=nothing
237If not fopen Then Exit Function
238
239Set ElementOBJ=ChildNode(XmlDom,ElementOBJ,false)
240If ElementOBJ Is Nothing Then Exit Function
241
242If IsCDATA=true Then
243set TextSection=XmlDom.createCDATASection(NewElementText)
244If ElementOBJ.firstchild Is Nothing Then
245ElementOBJ.appendChild TextSection
246ElseIf LCase(ElementOBJ.firstchild.nodeTypeString)="cdatasection" Then
247ElementOBJ.replaceChild TextSection,ElementOBJ.firstchild
248End If
249Else
250ElementOBJ.Text=NewElementText
251End If
252
253set fNode=ElementOBJ
254Set UpdateNodeText=ElementOBJ
255End Function
256
257'返回符合testValue条件的第一个ElementNode,为null就取当前默认对象
258Function getElementNode(byVal ElementName,byVal testValue)
259Dim Element,regEx,baseName
260
261Set getElementNode=nothing
262If not fopen Then Exit Function
263
264testValue=Trim(testValue)
265Set regEx=New RegExp
266regEx.Pattern="^[A-Za-z]+"
267regEx.IgnoreCase=true
268If regEx.Test(testValue) Then testValue="/"&testValue
269Set regEx=nothing
270
271baseName=LCase(Right(ElementName,Len(ElementName)-InStrRev(ElementName,"/",-1)))
272
273Set Element=XmlDom.SelectSingleNode("//"&ElementName&testValue)
274
275If Element Is Nothing Then
276'Response.write ElementName&testValue
277Set getElementNode=nothing
278Exit Function
279End If
280
281Do While LCase(Element.baseName)<>baseName
282Set Element=Element.selectSingleNode("..")
283If Element Is Nothing Then Exit Do
284Loop
285
286If LCase(Element.baseName)<>baseName Then
287Set getElementNode=nothing
288Else
289Set getElementNode=Element
290If Lcase(Element.nodeTypeString)="element" Then
291Set fNode=Element
292Else
293Set fANode=Element
294End If
295End If
296End Function
297
298'删除一个子节点
299Function removeChild(byVal ElementOBJ)
300removeChild=false
301If not fopen Then Exit Function
302
303Set ElementOBJ=ChildNode(null,ElementOBJ,false)
304If ElementOBJ Is Nothing Then Exit Function
305
306'response.write ElementOBJ.baseName
307
308If Lcase(ElementOBJ.nodeTypeString)="element" Then
309If ElementOBJ Is fNode Then set fNode=Nothing
310If ElementOBJ.parentNode Is Nothing Then
311XmlDom.removeChild(ElementOBJ)
312Else
313ElementOBJ.parentNode.removeChild(ElementOBJ)
314End If
315removeChild=True
316End If
317End Function
318
319'清空一个节点所有子节点
320Function ClearNode(byVal ElementOBJ)
321set ClearNode=Nothing
322If not fopen Then Exit Function
323
324Set ElementOBJ=ChildNode(null,ElementOBJ,false)
325If ElementOBJ Is Nothing Then Exit Function
326
327ElementOBJ.text=""
328ElementOBJ.removeChild(ElementOBJ.firstchild)
329
330Set ClearNode=ElementOBJ
331Set fNode=ElementOBJ
332End Function
333
334'删除子节点的一个属性
335Function removeAttributeNode(byVal ElementOBJ,byVal AttributeOBJ)
336removeAttributeNode=false
337If not fopen Then Exit Function
338
339Set ElementOBJ=ChildNode(XmlDom,ElementOBJ,false)
340If ElementOBJ Is Nothing Then Exit Function
341
342Set AttributeOBJ=ChildNode(ElementOBJ,AttributeOBJ,true)
343If not AttributeOBJ Is nothing Then
344ElementOBJ.removeAttributeNode(AttributeOBJ)
345removeAttributeNode=True
346End If
347End Function
348
349'保存打开过的文件,只要保证FileName不为空就可以实现保存
350Function Save()
351On Error Resume Next
352Save=false
353If (not fopen) or (fFileName="") Then Exit Function
354
355XmlDom.Save fFileName
356Save=(not IsError)
357If Err.number<>0 then
358Err.clear
359Save=false
360End If
361End Function
362
363'另存为XML文件,只要保证FileName不为空就可以实现保存
364Function SaveAs(SaveFileName)
365On Error Resume Next
366SaveAs=false
367If (not fopen) or SaveFileName="" Then Exit Function
368XmlDom.Save SaveFileName
369SaveAs=(not IsError)
370If Err.number<>0 then
371Err.clear
372SaveAs=false
373End If
374End Function
375
376'检查并打印错误信息
377Private Function IsError()
378If XmlDom.ParseError.errorcode<>0 Then
379fErrInfo="<h1>Error"&XmlDom.ParseError.errorcode&"</h1>"
380fErrInfo=fErrInfo&"<B>Reason :</B>"&XmlDom.ParseError.reason&"<br>"
381fErrInfo=fErrInfo&"<B>URL :</B>"&XmlDom.ParseError.url&"<br>"
382fErrInfo=fErrInfo&"<B>Line :</B>"&XmlDom.ParseError.line&"<br>"
383fErrInfo=fErrInfo&"<B>FilePos:</B>"&XmlDom.ParseError.filepos&"<br>"
384fErrInfo=fErrInfo&"<B>srcText:</B>"&XmlDom.ParseError.srcText&"<br>"
385IsError=True
386Else
387IsError=False
388End If
389End Function
390End Class
391%>
392