通过XmlDocument读写Xml文档参考地址

/// <summary>
/// 获取一个报表的参数  http://blog.csdn.net/hdhai9451/article/details/12170069
/// </summary>
public static ReportAdapterSection GetReportAdapterSectionByID(string ReportID, ProfileRole RoleType, ReportTemplateType TemplateType)
{
    ReportAdapterSection reportModel = new ReportAdapterSection();
    XmlDocument xmlDoc = new XmlDocument();
    string configFile = GetReportConfigFile(RoleType, TemplateType);
    xmlDoc.Load(configFile);
    XmlNodeList nodes = xmlDoc.SelectSingleNode("ReportConfig").ChildNodes;
    List<ReportParamSection> list = new List<ReportParamSection>();

    foreach (XmlElement node in nodes)
    {
        if (node.HasChildNodes && node.Attributes["ID"].Value == ReportID)
        {
            string MainID = node.Attributes["ID"].Value;
            reportModel.ID = MainID;
            reportModel.Title = node.Attributes["Title"].Value;
            string UniqueKey = string.Empty;
            if (node.Attributes["UniqueKey"] != null)
            {
                UniqueKey = node.Attributes["UniqueKey"].Value;
            }
            reportModel.UniqueKey = UniqueKey;
            string SummaryAmtOrNum = string.Empty;
            if (node.Attributes["SummaryAmtOrNum"] != null)
            {
                SummaryAmtOrNum = node.Attributes["SummaryAmtOrNum"].Value;
            }
            reportModel.SummaryAmtOrNum = SummaryAmtOrNum;

            bool IsAddTotal = false;
            if (node.Attributes["IsAddTotal"] != null)
            {
                IsAddTotal = node.Attributes["IsAddTotal"].Value == "1" ? true : false;
            }
            reportModel.IsAddTotal = IsAddTotal;
            XmlNode paramsNode = node.SelectSingleNode("Params");
            if (paramsNode != null && paramsNode.HasChildNodes)
            {
                foreach (XmlElement item in paramsNode)
                {
                    ReportParamSection model = new ReportParamSection();
                    model.MainID = MainID;
                    model.Title = item.Attributes["ParaTitle"].Value;
                    model.Type = (ReportParaType)Enum.Parse(typeof(ReportParaType), item.Attributes["ParaType"].Value);

                    //参数
                    string paras1 = string.Empty, paras2 = string.Empty;
                    paras1 = item.Attributes["Para1Name"].Value;
                    if (item.Attributes["Para2Name"] != null)
                    {
                        paras2 = item.Attributes["Para2Name"].Value;
                    }
                    model.Params = new string[] { paras1, paras2 };
                    //默认值
                    string dvalue1 = string.Empty, dvalue2 = string.Empty;
                    if (item.Attributes["Default1Value"] != null)
                    {
                        dvalue1 = item.Attributes["Default1Value"].Value;
                    }
                    if (item.Attributes["Default2Value"] != null)
                    {
                        dvalue2 = item.Attributes["Default2Value"].Value;
                    }
                    model.DefaultValues = new string[] { dvalue1, dvalue2 };
                    //条件标题
                    string ConditionTitle = string.Empty;
                    if (item.Attributes["ConditionTitle"] != null)
                    {
                        ConditionTitle = item.Attributes["ConditionTitle"].Value;
                    }
                    model.ConditionTitle = ConditionTitle;
                    list.Add(model);
                }
            }
            XmlNode sqlNode = node.SelectSingleNode("SqlStatement");
            reportModel.MasterSqlStatement = sqlNode.InnerText;
            if (node.SelectSingleNode("Remark1") != null)
            {
                reportModel.Remark1 = node.SelectSingleNode("Remark1").Attributes["Text"].Value;
            }
            if (node.SelectSingleNode("Remark2") != null)
            {
                reportModel.Remark2 = node.SelectSingleNode("Remark2").Attributes["Text"].Value;
            }
            if (node.SelectSingleNode("Remark3") != null)
            {
                reportModel.Remark3 = node.SelectSingleNode("Remark3").Attributes["Text"].Value;
            }
        }
    }
    reportModel.ParamSettings = list;
    return reportModel;
}
<?xml version="1.0" encoding="utf-8" ?>
<ReportConfig>
  <Report ID="1" Title="The InKindItem Information">
    <Params>
      <ParamItem ParaType="DateRange" ParaTitle="饋贈日期" Para1Name="@StartDate" Para2Name="@EndDate"  Default1Value="-365" Default2Value="0" ConditionTitle="InKindItemDate"/>
    </Params>
    <SqlStatement>
      <![CDATA[
select * 
from ProfileInKindItem
where InKindDate between @StartDate and @EndDate

    
        ]]>
    </SqlStatement>
  </Report>
</ReportConfig>

http://www.cnblogs.com/yukaizhao/archive/2011/07/19/csharp_xmldocument_access_xml.html

<?xml version="1.0" encoding="utf-8" ?>
<students>
  <!--我是一段注释文字-->
  <student name="张平">
    <courses>
      <course name="语文?">
        <teacherComment>
          <![CDATA[
        这里是语文老师的批注
        ]]>
        </teacherComment>      
    </course>
 
      <course name="数学">
        <teacherComment>
          <![CDATA[
        这里是数学老师的批注
        ]]>
        </teacherComment>
      </course>
    </courses>
  </student>
</students>

1.如何使用XmlDocument读取Xml

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
 
namespace XmlExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlFilePath = @"X:about.netexampleXmlExample1.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFilePath);
 
            //使用xpath表达式选择文档中所有的student子节点
            XmlNodeList studentNodeList = doc.SelectNodes("/students/student");
            if (studentNodeList != null)
            {
                foreach (XmlNode studentNode in studentNodeList)
                {
                    //通过Attributes获得属性名字为name的属性
                    string name = studentNode.Attributes["name"].Value;
                    Console.WriteLine("Student:" + name);
 
                    //通过SelectSingleNode方法获得当前节点下的courses子节点
                    XmlNode coursesNode = studentNode.SelectSingleNode("courses");
 
                    //通过ChildNodes属性获得courseNode的所有一级子节点
                    XmlNodeList courseNodeList = coursesNode.ChildNodes;
                    if (courseNodeList != null)
                    {
                        foreach (XmlNode courseNode in courseNodeList)
                        {
                            Console.Write("	");
                            Console.Write(courseNode.Attributes["name"].Value);
                            Console.Write("老师评语");
                            //通过FirstNode属性可以获得课程节点的第一个子节点,LastNode可以获得最后一个子节点
                            XmlNode teacherCommentNode = courseNode.FirstChild;
                            //读取CData节点
                            XmlCDataSection cdata = (XmlCDataSection)teacherCommentNode.FirstChild;
                            Console.WriteLine(cdata.InnerText.Trim());
                        }
                    }
                }
            }
 
            Console.Write("
Press any key to continue....");
            Console.Read();
        }
    }
}

2.如何通过XmlDocument编辑Xml

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
 
namespace WriteXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //创建Xml声明部分,即<?xml version="1.0" encoding="utf-8" ?>
            xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
 
            //创建根节点
            XmlNode rootNode = xmlDoc.CreateElement("students");
 
            //创建student子节点
            XmlNode studentNode = xmlDoc.CreateElement("student");
            //创建一个属性
            XmlAttribute nameAttribute = xmlDoc.CreateAttribute("name");
            nameAttribute .Value = "张同学";
            //xml节点附件属性
            studentNode.Attributes.Append(nameAttribute);
 
            
            //创建courses子节点
            XmlNode coursesNode = xmlDoc.CreateElement("courses");
            XmlNode courseNode1 = xmlDoc.CreateElement("course");
            XmlAttribute courseNameAttr = xmlDoc.CreateAttribute("name");
            courseNameAttr.Value = "语文";
            courseNode1.Attributes.Append(courseNameAttr);
            XmlNode teacherCommentNode = xmlDoc.CreateElement("teacherComment");
            //创建Cdata块
            XmlCDataSection cdata = xmlDoc.CreateCDataSection("<font color="red">这是语文老师的批注</font>");
            teacherCommentNode.AppendChild(cdata);
            courseNode1.AppendChild(teacherCommentNode);
            coursesNode.AppendChild(courseNode1);
            //附加子节点
            studentNode.AppendChild(coursesNode);
 
            rootNode.AppendChild(studentNode);
            //附加根节点
            xmlDoc.AppendChild(rootNode);
 
            //保存Xml文档
            xmlDoc.Save(@"d:	est.xml");
 
            Console.WriteLine("已保存Xml文档");
 
 
        }
    }
}
  //这只是一些写法            

              XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(this.ConfigString); XmlNode root = xmlDoc.DocumentElement; //取到根结点 XmlNode otNode = xmlDoc.SelectSingleNode("ShiftConfig/Ot"); XmlNode itemNode = xmlDoc.SelectSingleNode("ShiftConfig/Item"); XmlNodeList otNodeList = otNode.ChildNodes; XmlNodeList itemNodeList = itemNode.ChildNodes; if (otNodeList != null) { //TODO:把ot下面节点foreach,查看xml结构:SELECT CONVERT(XML,configstring), * FROM At_Shift ,下面的注释不用可以删除 foreach (XmlNode node in otNodeList) { } } if (itemNodeList != null) { //TODO:把item下面的节点foreach foreach (XmlNode node in otNodeList) { } } //XmlNode shiftConfigNode = xmlDoc.SelectSingleNode("ShiftConfig"); //if (otNode == null) //{ // //XmlElement xe1 = xmlDoc.CreateElement("Ot");//创建一个Ot节点 // //xe1.InnerText = "10.95"; // //xmlDoc.DocumentElement.AppendChild(xe1); // //XmlNode newNode = xmlDoc.CreateNode("element", "Ot", ""); // // newNode.InnerText = "WPF"; // // root.AppendChild(newNode);//添加为根元素的第一层子结点 // XmlNode deep1 = root.CloneNode(true); //克隆根节点 // //Console.WriteLine(deep.OuterXml); // XmlNode xx = xmlDoc.ImportNode(deep1, true); // root.AppendChild(xx);

http://www.cr173.com/html/23515_1.html

一 前言

先来了解下操作XML所涉及到的几个类及之间的关系  如果大家发现少写了一些常用的方法,麻烦在评论中指出,我一定会补上的!谢谢大家

* 1 XMLElement 主要是针对节点的一些属性进行操作
* 2 XMLDocument 主要是针对节点的CUID操作
* 3 XMLNode 为抽象类,做为以上两类的基类,提供一些操作节点的方法

清楚了以上的关系在操作XML时会更清晰一点

二 具体操作

以下会对Xml的结点与属性做增 删 改 查的操作也满足了实际工作中的大部分情况 

先构造一棵XML树如下,其中也涉及到了写入xml文档的操作

         public void CreatXmlTree(string xmlPath)
          {
              XElement xElement = new XElement(
                  new XElement("BookStore",
                      new XElement("Book",
                          new XElement("Name", "C#入门", new XAttribute("BookName", "C#")),
                          new XElement("Author", "Martin", new XAttribute("Name", "Martin")),
                          new XElement("Adress", "上海"),
                          new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
                         ),
                     new XElement("Book",
                         new XElement("Name", "WCF入门", new XAttribute("BookName", "WCF")),
                         new XElement("Author", "Mary", new XAttribute("Name", "Mary")),
                         new XElement("Adress", "北京"),
                         new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
                         )
                         )
                 );
 
             //需要指定编码格式,否则在读取时会抛:根级别上的数据无效。 第 1 行 位置 1异常
             XmlWriterSettings settings = new XmlWriterSettings();
             settings.Encoding = new UTF8Encoding(false);
             settings.Indent = true;
             XmlWriter xw = XmlWriter.Create(xmlPath,settings);
             xElement.Save(xw);
             //写入文件
             xw.Flush();
             xw.Close();
         }

然后得到如下的XML树

 <?xml version="1.0" encoding="utf-8"?>
  <BookStore>
      <Book>
         <Name BookName="C#">C#入门</Name>
         <Author Name="Martin">Martin</Author>
         <Date>2013-10-11</Date>
         <Adress>上海</Adress>
         <Date>2013-10-11</Date>
     </Book>
     <Book>
         <Name BookName="WCF">WCF入门</Name>
         <Author Name="Mary">Mary</Author>
         <Adress>北京</Adress>
         <Date>2013-10-11</Date>
     </Book>
 </BookStore>

以下操作都是对生成的XML树进行操作

2.1 新增节点与属性

新增节点NewBook并增加属性Name="WPF"

       public void Create(string xmlPath)
        {
             XmlDocument xmlDoc = new XmlDocument();
             xmlDoc.Load(xmlPath);
             
              var root = xmlDoc.DocumentElement;//取到根结点
             XmlNode newNode = xmlDoc.CreateNode("element", "NewBook", "");
              newNode.InnerText = "WPF";
  
              //添加为根元素的第一层子结点
              root.AppendChild(newNode);
             xmlDoc.Save(xmlPath);
         }

开篇有写操作xml节点属性主要用XmlElement对象所以取到结点后要转类型 

          //属性
           public void CreateAttribute(string xmlPath)
          {
               XmlDocument xmlDoc = new XmlDocument();
              xmlDoc.Load(xmlPath);
              var root = xmlDoc.DocumentElement;//取到根结点
               XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
              node.SetAttribute("Name", "WPF");
               xmlDoc.Save(xmlPath);
 
         }

效果如下

2.2 删除节点与属性

          public void Delete(string xmlPath)
          {
              XmlDocument xmlDoc = new XmlDocument();
              xmlDoc.Load(xmlPath);
             var root = xmlDoc.DocumentElement;//取到根结点
  
             var element = xmlDoc.SelectSingleNode("BookStore/NewBook");
               root.RemoveChild(element);
               xmlDoc.Save(xmlPath);
         }

删除属性

          public void DeleteAttribute(string xmlPath)
           {
             XmlDocument xmlDoc = new XmlDocument();
               xmlDoc.Load(xmlPath);
              XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
             //移除指定属性
             node.RemoveAttribute("Name");
              //移除当前节点所有属性,不包括默认属性
              //node.RemoveAllAttributes();
              xmlDoc.Save(xmlPath);
         }

2.3 修改节点与属性

xml的节点默认是不允许修改的,本文也就不做处理了

  修改属性代码如下

         public void ModifyAttribute(string xmlPath)
          {
             XmlDocument xmlDoc = new XmlDocument();
              xmlDoc.Load(xmlPath);
             XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
              element.SetAttribute("Name", "Zhang");
              xmlDoc.Save(xmlPath);
          }

效果如下

2.4 获取节点与属性

         public void Select(string xmlPath)
        {
               XmlDocument xmlDoc = new XmlDocument();
              xmlDoc.Load(xmlPath);
              //取根结点
             var root = xmlDoc.DocumentElement;//取到根结点
             //取指定的单个结点
             XmlNode oldChild = xmlDoc.SelectSingleNode("BookStore/NewBook");
              
              //取指定的结点的集合
              XmlNodeList nodes = xmlDoc.SelectNodes("BookStore/NewBook");
 
             //取到所有的xml结点
             XmlNodeList nodelist = xmlDoc.GetElementsByTagName("*");
        }

属性

        public void SelectAttribute(string xmlPath)
         {
             XmlDocument xmlDoc = new XmlDocument();
             xmlDoc.Load(xmlPath);
            XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
            string name = element.GetAttribute("Name");
             Console.WriteLine(name);
       }

三  linq to XML 操作

 Linq to Xml 也没什么变化只操作对象改变了主要涉及的几个对象如下   注:我并没有用linq的语法去操作元素。

XDocument:用于创建一个XML实例文档

XElement:用于一些节点与节点属性的基本操作

以下是对Xml的 一些简单的操作

3.1 新增节点与属性

         public void Create(string xmlPath)
         {
            XDocument xDoc = XDocument.Load(xmlPath);
             XElement xElement = xDoc.Element("BookStore");
             xElement.Add(new XElement("Test", new XAttribute("Name", "Zery")));
             xDoc.Save(xmlPath);
        }

属性

          public void CreateAttribute(string xmlPath)
          {
              XDocument xDoc = XDocument.Load(xmlPath);
              IEnumerable<XElement> xElement = xDoc.Element("BookStore").Elements("Book");
              foreach (var element in xElement)
              {
                  element.SetAttributeValue("Name", "Zery");
              }
              xDoc.Save(xmlPath);
         }

3.2 删除节点与属性

         public void Delete(string xmlPath)
         {
             XDocument xDoc = XDocument.Load(xmlPath);
             XElement element = (XElement)xDoc.Element("BookStore").Element("Book");
             element.Remove();
             xDoc.Save(xmlPath);
         }

属性

         public void DeleteAttribute(string xmlPath)
         {
             XDocument xDoc = XDocument.Load(xmlPath);
             //不能跨级取节点
             XElement element = xDoc.Element("BookStore").Element("Book").Element("Name");
             element.Attribute("BookName").Remove();
             xDoc.Save(xmlPath);
         }

3.3 修改节点属性

节点.net没提供修改的方法本文也不做处理

修改属性与新增实质是同一个方法

         public void ModifyAttribute(string xmlPath)
         {
             XDocument xDoc = XDocument.Load(xmlPath);
             XElement element = xDoc.Element("BookStore").Element("Book");
             element.SetAttributeValue("BookName","ZeryTest");
             xDoc.Save(xmlPath);
         }



http://www.cnblogs.com/youring2/archive/2008/12/08/1350319.html

常用公共属性: 

属性

说明

Attributes

MSDN:获取一个 XmlAttributeCollection,它包含该节点的属性。

注:对一个Xml节点操作的时候,返回的就是该节点的所有属性列表,可以通过下标访问,也可以通过属性名访问。

ChildNodes

MSDN:获取节点的所有子节点。

注:通过这个属性可以访问指定节点的所有子节点。

DocumentElement

MSDN:获取文档的根 XmlElement。

注:当文档有注释或者说明时候,必须通过该属性得到文档的根节点。如果文档只包含一个顶级节点,也可以通过FirstChild得到根。

FirstChild

MSDN:获取节点的第一个子级。

注:得到指定节点的第一个子节点。

NextSibling

MSDN:获取紧接在该节点之后的节点。

注:得到当前节点的下一个节点。

LastChild

MSDN:获取节点的最后一个子级。

注:获得当前节点的最后一个子节点。

InnerText

MSDN:获取或设置节点及其所有子节点的串联值。

注:得到所有子节点的值。这些值是串联起来的。类型为String。

InnerXml

MSDN:已重写。获取或设置表示当前节点子级的标记。

注:得到所有子节点的一个字符串。

OuterXml

MSDN:获取表示此节点及其所有子节点的标记。

注:得到包含当前节点的一个字符串。

Value

MSDN:获取或设置节点的值。

注:对节点的值进行操作。

表1、XmlDocument类常用属性

常用公共方法:

方法

说明

Load

MSDN:加载指定的 XML 数据。

注:加载一个Xml数据。可以从Stream中加载,也可以从文件加载。它具有四个重载。

LoadXml

MSDN:从指定的字符串加载 XML 文档。

注:从字符串加载Xml文档。如果该字符串不是Xml格式,则抛出异常。

AppendChild

MSDN:将指定的节点添加到该节点的子节点列表的末尾。

注:添加一个孩子节点。

CreateElement

MSDN:创建 XmlElement。

注:创建一个节点。该方法必须由Xml文档调用。

Save

MSDN:将 XML 文档保存到指定的位置。

注:保存Xml文档。可以保存到文件,也可以保存到数据流中。该方法同样有四个重载。

SelectNodes

MSDN:选择匹配 XPath 表达式的节点列表。

注:得到指定路径的所有节点列表。

SelectSingleNode

MSDN:选择匹配 XPath 表达式的第一个 XmlNode。

注:得到指定路径的第一个节点。即SelectNodes方法的列表的第一个元素。

表2、XmlDocument类常用方法

原文地址:https://www.cnblogs.com/shy1766IT/p/4947012.html