c# xml操作类

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();

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值