C# 创建及操作XML文件

XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null);
            doc.AppendChild(dec);
            //创建一个根节点(一级)
            XmlElement root = doc.CreateElement("First");
            doc.AppendChild(root);
            //创建节点(二级)
            XmlNode node = doc.CreateElement("Seconde");
            //创建节点(三级)
            XmlElement element1 = doc.CreateElement("Third1");
            element1.SetAttribute("Name", "Sam");
            element1.SetAttribute("ID", "665");
            element1.InnerText = "Sam Comment";
            node.AppendChild(element1);

            XmlElement element2 = doc.CreateElement("Third2");
            element2.SetAttribute("Name", "Round");
            element2.SetAttribute("ID", "678");
            element2.InnerText = "Round Comment";
            node.AppendChild(element2);

           

            root.AppendChild(node);
            doc.Save(@"d:\bb.xml");
            Console.Write(doc.OuterXml);

写的一个XML操作类,包括读取/插入/修改/删除。

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

namespace PuTianCheng
{
    /// <summary>
    /// XmlHelper 的摘要说明
    /// </summary>
    public class XmlHelper
    {
        public XmlHelper()
        {
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名,非空时返回该属性值,否则返回串联值</param>
        /// <returns>string</returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Read(path, "/Node", "")
         * XmlHelper.Read(path, "/Node/Element[@Attribute='Name']", "Attribute")
         ************************************************/
        public static string Read(string path, string node, string attribute)
        {
            string value = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value);
            }
            catch { }
            return value;
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="element">元素名,非空时插入新元素,否则在该元素中插入属性</param>
        /// <param name="attribute">属性名,非空时插入该元素属性值,否则插入元素值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Insert(path, "/Node", "Element", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Element", "Attribute", "Value")
         * XmlHelper.Insert(path, "/Node", "", "Attribute", "Value")
         ************************************************/
        public static void Insert(string path, string node, string element, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        XmlElement xe = (XmlElement)xn;
                        xe.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    XmlElement xe = doc.CreateElement(element);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    xn.AppendChild(xe);
                }
                doc.Save(path);
            }
            catch { }
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名,非空时修改该节点属性值,否则修改节点值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Insert(path, "/Node", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Attribute", "Value")
         ************************************************/
        public static void Update(string path, string node, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xe.InnerText = value;
                else
                    xe.SetAttribute(attribute, value);
                doc.Save(path);
            }
            catch { }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Delete(path, "/Node", "")
         * XmlHelper.Delete(path, "/Node", "Attribute")
         ************************************************/
        public static void Delete(string path, string node, string attribute)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xn.ParentNode.RemoveChild(xn);
                else
                    xe.RemoveAttribute(attribute);
                doc.Save(path);
            }
            catch { }
        }
    }
}

==================================================

XmlFile.xml:
<?xml version="1.0" encoding="utf-8"?>
<Root />

==================================================

使用方法:

string xml = Server.MapPath("XmlFile.xml");
//插入元素
//XmlHelper.Insert(xml, "/Root", "Studio", "", "");
//插入元素/属性
//XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "小路工作室");
//XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "丁香鱼工作室");
//XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "谱天城工作室");
//XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Master", "", "红尘静思");
//插入属性
//XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='小路工作室']", "", "Url", "http://www.wzlu.com/");
//XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='丁香鱼工作室']", "", "Url", "http://www.luckfish.net/");
//XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "", "Url", "http://www.putiancheng.com/");
//修改元素值
//XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']/Master", "", "RedDust");
//修改属性值
//XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Url", "http://www.putiancheng.net/");
//XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Name", "PuTianCheng Studio");
//读取元素值
//Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site/Master", "") + "</div>");
//读取属性值
//Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site", "Url") + "</div>");
//读取特定属性值
//Response.Write("<div>" + XmlHelper.Read(xml, "/Root/Studio/Site[@Name='丁香鱼工作室']", "Url") + "</div>");
//删除属性
//XmlHelper.Delete(xml, "/Root/Studio/Site[@Name='小路工作室']", "Url");
//删除元素
//XmlHelper.Delete(xml, "/Root/Studio", "");

-----分析XML数据-------

<?xml version="1.0" encoding="utf-8" ?>
<FlowER>  
  <SuccessFlag>True</SuccessFlag>
  <ReturnInfo>
    <ApproveRow>
      <App_Serial>1</App_Serial>
      <App_Emp_ID>057274</App_Emp_ID>
      <App_Emp_Name>彭媛(YUAN.PENGY)</App_Emp_Name>
      <App_YN></App_YN>
      <App_Date>2012/06/27 14:55:26</App_Date>
      <App_Act_ID>057274</App_Act_ID>
      <App_Act_Name>彭媛(YUAN.PENGY) </App_Act_Name>
      <App_Remark><![CDATA[]]></App_Remark>
      <App_Assigner>SYS.EMP.0</App_Assigner>
      <App_Login_Name>YUAN.PENGY</App_Login_Name>
      <Form_Approve_ID>ALIFMAP2805633</Form_Approve_ID>
      <Form_Kind>SYS.FORM.031</Form_Kind>
      <Form_NO>1000024</Form_NO>
      <Phase_ID>SYS.FORM.031.APPH.1</Phase_ID>
      <App_Type>A</App_Type>
      <Assign_Type>N</Assign_Type>
      <App_Status>T</App_Status>
      <App_Role><![CDATA[财务初审/Finance Initial]]></App_Role>
      <Assign_Reason><![CDATA[\r\n转签原因 : 1]]></Assign_Reason>
    </ApproveRow>
    <ApproveRow>
      <App_Serial>1</App_Serial>
      <App_Emp_ID>045862</App_Emp_ID>
      <App_Emp_Name>张建平(JIANPING.ZHANGJP)</App_Emp_Name>
      <App_YN></App_YN>
      <App_Date></App_Date>
      <App_Act_ID></App_Act_ID>
      <App_Act_Name>张建平(JIANPING.ZHANGJP) </App_Act_Name>
      <App_Remark><![CDATA[]]></App_Remark>
      <App_Assigner>057274</App_Assigner>
      <App_Login_Name>JIANPING.ZHANGJP</App_Login_Name>
      <Form_Approve_ID>ALIFMAP2805649</Form_Approve_ID>
      <Form_Kind>SYS.FORM.031</Form_Kind>
      <Form_NO>1000024</Form_NO>
      <Phase_ID>SYS.FORM.031.APPH.1</Phase_ID>
      <App_Type>A</App_Type>
      <Assign_Type>T</Assign_Type>
      <App_Status>U</App_Status>
      <App_Role><![CDATA[[彭媛(YUAN.PENGY) Transferred]]]></App_Role>
      <Assign_Reason><![CDATA[]]></Assign_Reason>
    </ApproveRow>
    <ApproveRow>
      <App_Serial>2</App_Serial>
      <App_Emp_ID>013307</App_Emp_ID>
      <App_Emp_Name>陈春波(CHUNBO.CHENCB)</App_Emp_Name>
      <App_YN></App_YN>
      <App_Date></App_Date>
      <App_Act_ID></App_Act_ID>
      <App_Act_Name>陈春波(CHUNBO.CHENCB) </App_Act_Name>
      <App_Remark><![CDATA[]]></App_Remark>
      <App_Assigner>SYS.EMP.0</App_Assigner>
      <App_Login_Name>CHUNBO.CHENCB</App_Login_Name>
      <Form_Approve_ID>ALIFMAP2805636</Form_Approve_ID>
      <Form_Kind>SYS.FORM.031</Form_Kind>
      <Form_NO>1000024</Form_NO>
      <Phase_ID>SYS.FORM.031.APPH.3</Phase_ID>
      <App_Type>A</App_Type>
      <Assign_Type>N</Assign_Type>
      <App_Status>W</App_Status>
      <App_Role><![CDATA[实际需求方上级主管/Actual Requester Manager]]></App_Role>
      <Assign_Reason><![CDATA[]]></Assign_Reason>
    </ApproveRow>
  </ReturnInfo>
</FlowER>

 分析XML数据C#代码

 方法一

View Code
XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(returnXml);

                string strApproveName = string.Empty;
                string strFormStatus = string.Empty;

                XmlNodeList nodeList = xmlDoc.SelectSingleNode("/FlowER/ReturnInfo").ChildNodes;

                foreach (XmlNode node in nodeList)
                {
                    strApproveName=string.Empty;
                    strFormStatus=string.Empty;

                    XmlElement xe1 = (XmlElement)node;
                    foreach (XmlNode xd in xe1.ChildNodes)
                    {
                        XmlElement xe2=(XmlElement)xd;
                        if (xe2.Name.ToUpper() == "APP_STATUS")
                        {
                            strFormStatus = xe2.InnerText.ToUpper();
                        }
                        if (xe2.Name.ToUpper() == "APP_EMP_NAME")
                        {
                            strApproveName = xe2.InnerText;
                        }
                    }
                    if (strFormStatus == "U")
                    {
                        break;
                    }
                }

 方法二

View Code
 string approveName = "";
                using (XmlReader xmlReader = XmlTextReader.Create(new StringReader(returnXml)))
                {

                    string appEmpName = "";
                    string appYn = "appYn";
                    string appDate = "";
                    while (xmlReader.Read())
                    {
                        if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "App_Emp_Name")
                        {
                            appEmpName = xmlReader.ReadString();
                        }
                        if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "App_YN")
                        {
                            appYn = xmlReader.ReadString();
                        }
                        if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "App_Date")
                        {
                            appDate = xmlReader.ReadString();
                        }
                        if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.LocalName == "ApproveRow")
                        {
                            if (appYn.Length == 0 && appDate.Length == 0)
                            {
                                approveName = appEmpName;
                                break;
                            }
                        }
                    }
                }
原文地址:https://www.cnblogs.com/huanghai223/p/2148946.html