C#操作Xml全集示例篇,基本实现添加,删除,更新等操作

using System;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Web;
namespace Library.ClassLibrary.XML
{
    
/// <summary>
    
/// xml 的摘要说明。
    
/// </summary>

    public class XML
    
{
        
public enum enumXmlPathType
        
{
            AbsolutePath,
            VirtualPath
        }

        
private string xmlFilePath ;
        
private enumXmlPathType xmlFilePathType ;
        
private XmlDocument xmlDoc = new XmlDocument() ;
        
public string XmlFilePath
        
{
            
set
            
{
                xmlFilePath 
= value ;
            }

        }

        
public enumXmlPathType XmlFilePathTyp
        
{
            
set
            
{
                xmlFilePathType 
= value ;
            }

        }

        
public XML( string tempXmlFilePath )
        
{
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
            this.xmlFilePathType = enumXmlPathType.VirtualPath ;
            
this.xmlFilePath = tempXmlFilePath ;
            GetXmlDocument() ;
            
//xmlDoc.Load( xmlFilePath ) ;
        }

        
public XML( string tempXmlFilePath , enumXmlPathType tempXmlFilePathType )
        
{
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
            this.xmlFilePathType = tempXmlFilePathType ;
            
this.xmlFilePath = tempXmlFilePath ;
            GetXmlDocument() ;
        }

        
/// </summary>
        
/// <param name="strEntityTypeName">实体类的名称</param>
        
/// <returns>指定的XML描述文件的路径</returns>

        private XmlDocument GetXmlDocument()
        
{
            XmlDocument doc
=null;
            
ifthis.xmlFilePathType == enumXmlPathType.AbsolutePath )
            
{
                doc 
= GetXmlDocumentFromFile( xmlFilePath ) ;
            }

            
else ifthis.xmlFilePathType == enumXmlPathType.VirtualPath )
            
{
                doc 
= GetXmlDocumentFromFile(HttpContext.Current.Server.MapPath(xmlFilePath)) ;
            }

            
return doc;
        }

        
private XmlDocument GetXmlDocumentFromFile(string tempXmlFilePath)
        
{
            
string xmlFileFullPath = tempXmlFilePath ;
                    xmlDoc.Load(xmlFileFullPath) ;
            
return xmlDoc ;
        }

        
#region 读取指定节点的指定属性值
        
/// <summary>
        
/// 功能:
        
/// 读取指定节点的指定属性值
        
/// 
        
/// 参数:
        
/// 参数一:节点名称
        
/// 参数二:此节点的属性
        
/// </summary>
        
/// <param name="strNode"></param>
        
/// <param name="strAttribute"></param>
        
/// <returns></returns>

        public string GetXmlNodeValue(string strNode,string strAttribute)
        
{
            
string strReturn = "";
            
try
            
{
                
//根据指定路径获取节点
                XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode) ;            
                
//获取节点的属性,并循环取出需要的属性值
                XmlAttributeCollection xmlAttr = xmlNode.Attributes ;
                
for(int i=0 ;i<xmlAttr.Count; i++)
                
{
                    
if (xmlAttr.Item(i).Name == strAttribute)
                        strReturn 
= xmlAttr.Item(i).Value ;
                }

            }

            
catch(XmlException xmle)
            
{
                
throw xmle ;
            }

            
return strReturn ;
        }

        
#endregion

 

        
#region
        
/// <summary>
        
/// 功能:
        
/// 读取指定节点的值
        
/// 
        
/// 参数:
        
/// 参数:节点名称
        
/// </summary>
        
/// <param name="strNode"></param>
        
/// <returns></returns>

        public string GetXmlNodeValue(string strNode)
        
{
            
string strReturn = String.Empty ;
            
try
            
{
                
//根据路径获取节点
                XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode) ;
                strReturn 
= xmlNode.InnerText ;
            }

            
catch(XmlException xmle)
            
{
                System.Console.WriteLine(xmle.Message) ;
            }

            
return strReturn ;
        }

        
#endregion

        
#region 设置节点值
        
/// <summary>
        
/// 功能:
        
/// 设置节点值
        
/// 
        
/// 参数:
        
///    参数一:节点的名称
        
///    参数二:节点值
        
///    
        
/// </summary>
        
/// <param name="strNode"></param>
        
/// <param name="newValue"></param>

        public void SetXmlNodeValue(string xmlNodePath,string xmlNodeValue)
        
{
            
try
            
{
                
//根据指定路径获取节点
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xmlNodePath) ;            
                
//设置节点值
                xmlNode.InnerText = xmlNodeValue ;
            }

            
catch(XmlException xmle)
            
{
                
throw xmle ;
            }

        }

        
#endregion

        
#region 设置节点的属性值
        
/// <summary>
        
/// 功能:
        
/// 设置节点的属性值
        
/// 
        
/// 参数:
        
/// 参数一:节点名称
        
/// 参数二:属性名称
        
/// 参数三:属性值
        
/// 
        
/// </summary>
        
/// <param name="xmlNodePath"></param>
        
/// <param name="xmlNodeAttribute"></param>
        
/// <param name="xmlNodeAttributeValue"></param>

        public void SetXmlNodeValue(string xmlNodePath,string xmlNodeAttribute,string xmlNodeAttributeValue)
        
{
            
try
            
{
                
//根据指定路径获取节点
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xmlNodePath) ;
            
                
//获取节点的属性,并循环取出需要的属性值
                XmlAttributeCollection xmlAttr = xmlNode.Attributes ;
                
for(int i=0 ; i<xmlAttr.Count ; i++)
                
{
                    
if ( xmlAttr.Item(i).Name == xmlNodeAttribute )
                    
{
                        xmlAttr.Item(i).Value 
= xmlNodeAttributeValue;
                        
break ;
                    }

                }

            }

            
catch(XmlException xmle)
            
{
                
throw xmle ;
            }

        }

        
#endregion

        
/// <summary>
        
/// 获取XML文件的根元素
        
/// </summary>

        public XmlNode GetXmlRoot()
        
{
            
return xmlDoc.DocumentElement ;
        }

        
/// <summary>
        
/// 在根节点下添加父节点
        
/// </summary>

        public void AddParentNode(string parentNode)
        
{
            XmlNode root 
= GetXmlRoot() ;
            XmlNode parentXmlNode 
= xmlDoc.CreateElement(parentNode) ;
            root.AppendChild(parentXmlNode) ;
        }

        
/// <summary>
        
/// 向一个已经存在的父节点中插入一个子节点
        
/// </summary>

        public void AddChildNode( string parentNodePath,string childNodePath )
        
{
            XmlNode parentXmlNode 
= xmlDoc.SelectSingleNode(parentNodePath) ;
            XmlNode childXmlNode 
= xmlDoc.CreateElement(childNodePath) ;
            parentXmlNode.AppendChild( childXmlNode ) ;
        }

        
/// <summary>
        
/// 向一个节点添加属性
        
/// </summary>

        public void AddAttribute( string NodePath , string NodeAttribute)
        
{
            XmlAttribute nodeAttribute 
= xmlDoc.CreateAttribute(NodeAttribute) ;
            XmlNode nodePath 
= xmlDoc.SelectSingleNode( NodePath ) ;
            nodePath.Attributes.Append(nodeAttribute) ;
        }

        
/// <summary>
        
/// 删除一个节点的属性
        
/// </summary>

        public void DeleteAttribute( string NodePath , string NodeAttribute , string NodeAttributeValue)
        
{
            XmlNodeList nodePath 
= xmlDoc.SelectSingleNode( NodePath ).ChildNodes;
            
foreach(XmlNode xn in nodePath)
            
{
                XmlElement xe
=(XmlElement)xn;
                
if(xe.GetAttribute(NodeAttribute)==NodeAttributeValue)
                
{
                    xe.RemoveAttribute(NodeAttribute);
//删除属性
                }

            }

        }

        
/// <summary>
        
/// 删除一个节点
        
/// </summary>

        public void DeleteXmlNode(string tempXmlNode)
        
{
            
//XmlNodeList xmlNodePath=xmlDoc.SelectSingleNode(tempXmlNode).ChildNodes;
            XmlNode xmlNodePath = xmlDoc.SelectSingleNode( tempXmlNode ) ;
            xmlNodePath.ParentNode.RemoveChild( xmlNodePath ) ;
            
//foreach(XmlNode xn in xmlNodePath)
            
//{
                
//XmlElement xe=(XmlElement)xn;
                
//xe.RemoveAll();
                
//xe.RemoveChild(xn);
                
//xn.RemoveAll();
                
//if(xe.HasChildNodes)
                
//{
                    
//foreach(XmlNode xn in xe)
                    
//{
                        
//xn.RemoveAll();//删除所有子节点和属性
                    
//}
                
//}
            
//}
        }


        
#region 保存XML文件
        
/// <summary>
        
/// 功能: 
        
/// 保存XML文件
        
/// 
        
/// </summary>

        public void SaveXmlDocument()
        
{
            
try
            
{
                
//保存设置的结果
                xmlDoc.Save( HttpContext.Current.Server.MapPath( xmlFilePath ) );
            }

            
catch(XmlException xmle)
            
{
                
throw xmle;
            }

        }

        
#endregion

 
 
        
#region 保存XML文件
        
/// <summary>
        
/// 功能: 
        
/// 保存XML文件
        
/// 
        
/// </summary>

        public void SaveXmlDocument(string tempXMLFilePath)
        
{
            
try
            
{
                
//保存设置的结果
                xmlDoc.Save(tempXMLFilePath);
            }

            
catch(XmlException xmle)
            
{
                
throw xmle;
            }

        }

        
#endregion

 
    }

}


XmlAction.aspx文件
<%@ Page language="c#" Codebehind="XmlAction.aspx.cs" AutoEventWireup="false" Inherits="Web.Club.Xml2004.XmlAction" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    
<HEAD>
        
<title>test</title>
        
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        
<meta name="CODE_LANGUAGE" Content="C#">
        
<meta name="vs_defaultClientScript" content="JavaScript">
        
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    
</HEAD>
    
<body MS_POSITIONING="GridLayout">
        
<form id="Form1" method="post" runat="server">
            
<asp:Button id="btnAdd" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 88px" runat="server"
                Text
="添加Data节点"></asp:Button>
            
<asp:Button id="btnDelete" style="Z-INDEX: 102; LEFT: 176px; POSITION: absolute; TOP: 88px"
                runat
="server" Text="删除最后一个节点"></asp:Button>
            
<asp:Button id="btnModify" style="Z-INDEX: 103; LEFT: 360px; POSITION: absolute; TOP: 88px"
                runat
="server" Width="144px" Text="修改节点值"></asp:Button>
            
<asp:Button id="btnModifyAttribute" style="Z-INDEX: 104; LEFT: 368px; POSITION: absolute; TOP: 136px"
                runat
="server" Width="136px" Height="24px" Text="修改节点的属性值"></asp:Button>
        
</form>
    
</body>
</HTML>

XmlAction.cs文件
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Library.ClassLibrary.XML;
namespace Web.Club.Xml2004
{
    
/// <summary>
    
/// test 的摘要说明。
    
/// </summary>

    public class XmlAction : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Button btnAdd;
        
protected System.Web.UI.WebControls.Button btnDelete;
        
protected System.Web.UI.WebControls.Button btnModify;
        
protected System.Web.UI.WebControls.Button btnModifyAttribute;
    
        
protected XML myXML;
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面
            myXML=new XML("test.xml");
        }

        
#region Web 窗体设计器生成的代码
        
override protected void OnInit(EventArgs e)
        
{
            
//
            
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            
//
            InitializeComponent();
            
base.OnInit(e);
        }

        
        
/// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>

        private void InitializeComponent()
        
{    
            
this.btnAdd.Click += new System.EventHandler(this.btnAdd_OnClick);
            
this.btnDelete.Click += new System.EventHandler(this.btnDelete_OnClick);
            
this.btnModify.Click += new System.EventHandler(this.btnModifyNode_OnClick);
            
this.btnModifyAttribute.Click += new System.EventHandler(this.btnModifyAttribute_OnClick);
            
this.Load += new System.EventHandler(this.Page_Load);
        }

        
#endregion

        
private void btnAdd_OnClick(object sender, System.EventArgs e)
        
{
        
            
string tempDates = System.DateTime.Now.ToString();
            myXML.AddParentNode(
"Data");
            myXML.AddChildNode(
"//Data[last()]","Id");
            myXML.SetXmlNodeValue(
"//Data[last()]/Id",Session.SessionID.ToString()+Guid.NewGuid().ToString());
            myXML.AddChildNode(
"//Data[last()]","Subject");
            myXML.SetXmlNodeValue(
"//Data[last()]/Subject","这是第一个测试");
            myXML.AddChildNode(
"//Data[last()]","Content");
            myXML.SetXmlNodeValue(
"//Data[last()]/Content","好象还是有点问题,添加节点的时候XPath有点麻烦!");
            myXML.AddChildNode(
"//Data[last()]","Img");
                myXML.AddAttribute(
"//Data[last()]/Img","hasImg");
                myXML.SetXmlNodeValue(
"//Data[last()]/Img","hasImg","1");
                    myXML.AddChildNode(
"//Data[last()]/Img","ImgUrl");
                    myXML.SetXmlNodeValue(
"//Data[last()]/Img/ImgUrl","http://172.16.26.99/text.jpg");
            myXML.AddChildNode(
"//Data[last()]","Dates");
            myXML.SetXmlNodeValue(
"//Data[last()]/Dates",tempDates);
            myXML.SaveXmlDocument();
        }

        
private void btnDelete_OnClick(object sender, System.EventArgs e)
        
{
            myXML.DeleteXmlNode(
"//Data[last()]");
            myXML.SaveXmlDocument();
        
        }

        
private void btnModifyNode_OnClick(object sender, System.EventArgs e)
        
{
        
            myXML.SetXmlNodeValue(
"//Data[last()]/Subject","已经被修改");
            myXML.SaveXmlDocument();
        }

        
private void btnModifyAttribute_OnClick(object sender, System.EventArgs e)
        
{
        
            myXML.SetXmlNodeValue(
"//Data[last()]/Img","hasImg","0");
            myXML.SaveXmlDocument();
        }

    }

}


XmlAction.sxd文件
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="testSchema" targetNamespace="http://tempuri.org/testSchema.xsd" elementFormDefault="qualified"
    xmlns
="http://tempuri.org/testSchema.xsd" xmlns:mstns="http://tempuri.org/testSchema.xsd"
    xmlns:xs
="http://www.w3.org/2001/XMLSchema">
    
<xs:element name="Blog">
        
<xs:complexType>
            
<xs:sequence>
                
<xs:element name="Id" type="xs:int"></xs:element>
                
<xs:element name="Subject" type="xs:string" />
                
<xs:element name="Content" type="xs:string" />
                
<xs:element name="Img">
                    
<xs:complexType>
                        
<xs:sequence>
                            
<xs:element name="ImgUrl" />
                        
</xs:sequence>
                        
<xs:attribute name="hasImg" type="xs:int" />
                    
</xs:complexType>
                
</xs:element>
                
<xs:element name="Dates" type="xs:dateTime" />
            
</xs:sequence>
        
</xs:complexType>
    
</xs:element>
</xs:schema>

XmlAction.xml文件
<?xml version="1.0" encoding="utf-8"?>
<Blog>
  
<Data>
    
<Id>0</Id>
    
<Subject>My First Test</Subject>
    
<Content>OK...</Content>
    
<Img hasImg="1">
      
<ImgUrl>http://172.16.26.99/test.jpg</ImgUrl>
    </Img>
    
<Dates>2004-08-14</Dates>
  
</Data>
  
<Data>
    
<Id>2dah53nr5viplyqga5w5ws45e0573bec-69be-4e5c-9ac5-bb028adbe98f</Id>
    
<Subject>这是第一个测试</Subject>
    
<Content>好象还是有点问题,添加节点的时候XPath有点麻烦!</Content>
    
<Img hasImg="1">
      
<ImgUrl>http://172.16.26.99/text.jpg</ImgUrl>
    </Img>
    
<Dates>2004-8-18 23:04:07</Dates>
  
</Data>
  
<Data>
    
<Id>2dah53nr5viplyqga5w5ws45653396b4-cf18-4288-966d-fa6385033fb1</Id>
    
<Subject>这是第一个测试</Subject>
    
<Content>好象还是有点问题,添加节点的时候XPath有点麻烦!</Content>
    
<Img hasImg="1">
      
<ImgUrl>http://172.16.26.99/text.jpg</ImgUrl>
    </Img>
    
<Dates>2004-8-18 23:04:10</Dates>
  
</Data>
  
<Data>
    
<Id>2dah53nr5viplyqga5w5ws45b6f03405-4c0d-4ba5-bba5-12e42b211dac</Id>
    
<Subject>这是第一个测试</Subject>
    
<Content>好象还是有点问题,添加节点的时候XPath有点麻烦!</Content>
    
<Img hasImg="0">
      
<ImgUrl>http://172.16.26.99/text.jpg</ImgUrl>
    </Img>
    
<Dates>2004-8-18 23:04:11</Dates>
  
</Data>
</Blog> 

 

http://blog.csdn.net/lg836/archive/2007/07/01/1674814.aspx

你可能感兴趣的:(C#操作Xml全集示例篇,基本实现添加,删除,更新等操作)