需要添加的命名空间:
using System.Xml;

一、创建xml文件:

1、XmlDocument方式创建

XmlDocument xmldoc = new XmlDocument();
//加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
XmlDeclaration xmldecl;
xmldecl = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
xmldoc.AppendChild(xmldecl);

//加入一个根元素
XmlElement xmlelem = xmldoc.CreateElement("", "Employees", "");
xmldoc.AppendChild(xmlelem);
//加入另外一个元素
; i < ; i++)
{
    XmlNode root = xmldoc.SelectSingleNode("Employees");//查找<Employees>
    XmlElement xe1 = xmldoc.CreateElement("Node");//创建一个<Node>节点
    xe1.SetAttribute("genre", "李赞红");//设置该节点genre属性
    xe1.SetAttribute("ISBN", "2-3631-4");//设置该节点ISBN属性 

    XmlElement xesub1 = xmldoc.CreateElement("title");
    xesub1.InnerText = "CS从入门到精通";//设置文本节点 

    xe1.AppendChild(xesub1);//添加到<Node>节点中 

    XmlElement xesub2 = xmldoc.CreateElement("author");
    xesub2.InnerText = "候捷";
    xe1.AppendChild(xesub2);
    XmlElement xesub3 = xmldoc.CreateElement("price");
    xesub3.InnerText = "58.3";
    xe1.AppendChild(xesub3);

    root.AppendChild(xe1);//添加到<Employees>节点中 

}
//保存创建好的XML文档
xmldoc.Save("../../data.xml");

结果:生成了名为data.xml的文件,内容如下,

<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
</Employees>

2、XmlTextWriter方式创建

参见:XmlReader与 XMLWriter(抽象类)

string strFilename = "../../data1.xml";

XmlTextWriter xmlWriter = new XmlTextWriter(strFilename, Encoding.Default);//创建一个xml文档
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Employees");

xmlWriter.WriteStartElement("Node");
xmlWriter.WriteAttributeString("genre", "李赞红");
xmlWriter.WriteAttributeString("ISBN", "2-3631-4");

xmlWriter.WriteStartElement("title");
xmlWriter.WriteString("CS从入门到精通");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("author");
xmlWriter.WriteString("候捷");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("price");
xmlWriter.WriteString("58.3");
xmlWriter.WriteEndElement();

xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();

xmlWriter.Close();

结果:

<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
</Employees>

3、加载已有的XML文件:XmlDocument.Load()

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("data.xml"));

XmlElement root = xmldoc.DocumentElement;//获取根元素
foreach (XmlNode node in root.ChildNodes)
{
    if (node.Attributes["gere"].Value == "a")
    {
        foreach (XmlNode node1 in node.ChildNodes)
        {
            if (node1.Name == "author")
            {
                node1.InnerText = "aa";//修改文本
            }
        }
    }
}

4、创建XML片段:XmlDocument.CreateDocumentFragment()

XmlDocument xmldoc = new XmlDocument();
XmlDocumentFragment docFrag = xmldoc.CreateDocumentFragment();
docFrag.InnerXml = "<item>aa</item>";
Console.Write(docFrag.InnerXml);
XmlElement root = xmldoc.DocumentElement;
root.AppendChild(docFrag);

二、添加一个结点:AppendChild

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("../../data.xml");
XmlNode root = xmlDoc.SelectSingleNode("Employees");//查找<Employees> 

XmlElement xe1 = xmlDoc.CreateElement("Node");//创建一个<Node>节点 

xe1.SetAttribute("genre", "张三");//设置该节点genre属性
xe1.SetAttribute("ISBN", "1-1111-1");//设置该节点ISBN属性 

XmlElement xesub1 = xmlDoc.CreateElement("title");
xesub1.InnerText = "C#入门帮助";//设置文本节点 

xe1.AppendChild(xesub1);//添加到<Node>节点中 

XmlElement xesub2 = xmlDoc.CreateElement("author");
xesub2.InnerText = "高手";
xe1.AppendChild(xesub2);

XmlElement xesub3 = xmlDoc.CreateElement("price");
xesub3.InnerText = "158.3";
xe1.AppendChild(xesub3);

root.AppendChild(xe1);//添加到<Employees>节点中 

xmlDoc.Save("../../data.xml");

结果:在xml原有的内容里添加了一个结点,内容如下,

<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="张三" ISBN="1-1111-1">
    <title>C#入门帮助</title>
    <author>高手</author>
    <price>158.3</price>
  </Node>
</Employees>

三、修改结点的值(属性和子结点):

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("../../data.xml");

XmlNodeList nodeList = xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点 

foreach (XmlNode xn in nodeList)//遍历所有子节点
{
    XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
    if (xe.GetAttribute("genre") == "张三")//如果genre属性值为“张三”
    {
        xe.SetAttribute("genre", "update张三");//则修改该属性为“update张三”
        XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点
        foreach (XmlNode xn1 in nls)//遍历
        {
            XmlElement xe2 = (XmlElement)xn1;//转换类型
            if (xe2.Name == "author")//如果找到
            {
                xe2.InnerText = "亚胜";//则修改
            }
        }
    }
}
xmlDoc.Save("../../data.xml");//保存。

结果:将原来的所有结点的信息都修改了,xml的内容如下,

<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="update张三" ISBN="1-1111-1">
    <title>C#入门帮助</title>
    <author>亚胜</author>
    <price>158.3</price>
  </Node>
</Employees>

四、修改结点(添加结点的属性和添加结点的自结点)

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("../../data.xml");

XmlNodeList nodeList = xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点 

foreach (XmlNode xn in nodeList)
{
    XmlElement xe = (XmlElement)xn;
    xe.SetAttribute(");//添加属性

    XmlElement xesub = xmlDoc.CreateElement("flag");
    xesub.InnerText = ";
    xe.AppendChild(xesub);//添加子节点
}
xmlDoc.Save("../../data.xml");

结果:每个结点的属性都添加了一个,子结点也添加了一个,内容如下,

<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4" test="111111">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
    <flag>1</flag>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4" test="111111">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
    <flag>1</flag>
  </Node>
  <Node genre="update张三" ISBN="1-1111-1" test="111111">
    <title>C#入门帮助</title>
    <author>亚胜</author>
    <price>158.3</price>
    <flag>1</flag>
  </Node>
</Employees>

五、删除结点中的某一个属性:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("../../data.xml");

XmlNodeList xnl = xmlDoc.SelectSingleNode("Employees").ChildNodes;
foreach (XmlNode xn in xnl)
{
    XmlElement xe = (XmlElement)xn;
    xe.RemoveAttribute("genre");//删除genre属性 

    XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点 

    foreach (XmlNode xn1 in nls)//遍历
    {
        XmlElement xe2 = (XmlElement)xn1;//转换类型 

        if (xe2.Name == "flag")//如果找到
        {
            xe.RemoveChild(xe2);//则删除
        }
    }
}
xmlDoc.Save("../../data.xml");

结果:删除了结点的一个属性和结点的一个子结点,内容如下,

<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node ISBN="2-3631-4" test="111111">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node ISBN="2-3631-4" test="111111">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node ISBN="1-1111-1" test="111111">
    <title>C#入门帮助</title>
    <author>亚胜</author>
    <price>158.3</price>
  </Node>
</Employees>

六、删除结点:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("../../data.xml");

XmlNode root = xmlDoc.SelectSingleNode("Employees");
XmlNodeList xnl = xmlDoc.SelectSingleNode("Employees").ChildNodes;
; i < xnl.Count; i++)
{
    XmlElement xe = (XmlElement)xnl.Item(i);
    if (xe.GetAttribute("genre") == "张三")
    {
        root.RemoveChild(xe);
        ;
    }
}
xmlDoc.Save("../../data.xml");

结果:删除了符合条件的所有结点,原来的内容:

<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="张三" ISBN="1-1111-1">
    <title>C#入门帮助</title>
    <author>高手</author>
    <price>158.3</price>
  </Node>
  <Node genre="张三" ISBN="1-1111-1">
    <title>C#入门帮助</title>
    <author>高手</author>
    <price>158.3</price>
  </Node>
</Employees>

删除后的内容:

<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
</Employees>

七、替换子元素

XmlElement  elem=xmldoc.CreateElement("title");
elem.InnerText="XX";
root.ReplaceChild(elem,root.FirstChild);

八、按照文本文件读取xml:StreamReader

StreamReader myFile = new StreamReader("../../data.xml", System.Text.Encoding.Default);
//注意System.Text.Encoding.Default

string myString = myFile.ReadToEnd();//myString是读出的字符串
myFile.Close();

Console.Write(myString);

二、操作XML DOM:XML Document的更多相关文章

  1. XML DOM(Document Object Model)

    1.XML DOM 是用于获取.更改.添加或删除 XML 元素的标准.2.节点(XML 文档中的每个成分都是一个节点):        整个文档是一个文档节点:        每个XML元素是一个元素 ...

  2. xml dom minidom

    一. xml相关术语: 1.Document(文档): 对应一个xml文件 2.Declaration(声明): <?xml version="1.0" encoding=& ...

  3. 雷林鹏分享:XML DOM

    XML DOM DOM(Document Object Model 文档对象模型)定义了访问和操作文档的标准方法. XML DOM XML DOM(XML Document Object Model) ...

  4. XML DOM 知识点

    第一部分[DOM基础] DOM介绍: 1.什么是 HTML DOM? HTML DOM 定义了所有 HTML 元素的对象和属性,以及访问它们的方法(接口). 2.什么是 XML DOM? XML DO ...

  5. Commons JXPath - DOM/JDOM Document Access

    除了 JavaBean,JXPath 也可以访问 DOM/JDOM. 示例 XML: <?xml version="1.0" encoding="utf-8&quo ...

  6. XML DOM (Document Object Model) 定义了访问和操作 XML 文档的标准方法。

    XML DOM DOM 把 XML 文档视为一种树结构.通过这个 DOM 树,可以访问所有的元素.可以修改它们的内容(文本以及属性),而且可以创建新的元素.元素,以及它们的文本和属性,均被视为节点. ...

  7. Java SE之XML<二>XML DOM与SAX解析

    [文档整理系列] Java SE之XML<二>XML DOM与SAX解析 XML编程:CRUD(Create Read Update Delete) XML解析的两种常见方式: DOM(D ...

  8. 【二十八】xml编程(dom\xpath\simplexml)

    1.xml基础概念 作用范围: 作为程序通讯的标准. 作为配置文件. 作为小型数据库. xml语法: <根标签> <标签 元素="元素值" ...>< ...

  9. xml ---DOM操作

    package day03.xml; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; ...

  10. PHP使用DOM XML操作XML[总结]

    1.前言 XML树状层次结构鲜明,非常适合作为配置文件.PHP中可以使用DOM XML来操作XML.本文总结一下PHP使用DOM XML创建.添加节点.查询XML文件. 2.使用DOM XML XML ...

随机推荐

  1. CMS之promotion failed&concurrent mode failure

    原文链接:https://www.jianshu.com/p/ca1b0d4107c5 CMS并行GC收集器是大多数JAVA服务应用的最佳选择,然而, CMS并不是完美的,在使用CMS的过程中会产生2 ...

  2. 网页授权access_token,基础支持access_token,jsapi_ticket

    微信开发中网页授权access_token与基础支持的access_token异同 问题1:网页授权access_token与分享的jssdk中的access_token一样吗? 答:不一样.网页授权 ...

  3. LeetCode 20. 有效的括号(Valid Parentheses)

    20. 有效的括号 20. Valid Parentheses 题目描述 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须 ...

  4. [转帖]Hadoop与Spark比较

    Hadoop与Spark比较 https://www.cnblogs.com/charlesblc/p/6206198.html 感觉自己落下好多东西没有学习 先看这篇文章:http://www.hu ...

  5. C++ 获取系统当前时间(日历时)

    获取系统当前时间(日历时) //Linux & C++11 #include <chrono> #include <ctime> using namespace std ...

  6. docker 实践五:端口映射和容器互联

    本篇是关于 docker 容器的端口映射和容器之间的互联内容. 注:环境为 CentOS7,docker 19.03. docker 的容器除了能连接网络外,在许多时候,我们需要让多个容器来协同完成任 ...

  7. idea .gitignore模板

    IDEA 创建的项目,需要搞个.gitignore文件,文件内容可以参考插件的. # Created by .ignore support plugin (hsz.mobi) ### JetBrain ...

  8. javascript 之 call,apply原理

    一.call原理 1.使用JQuery的call功能 var add(c,d){ return this.a+this.b+c+d } var obj={a:1,b:2} add.Call(obj,3 ...

  9. .NetCore/ .NetFramework 机制

    1.每来一个请求,会启动一个线程. 可以通过下面代码打印出来. 这个线程是主线程,如果用异步,会等待异步线程执行完毕才会返回. 这有个现象,用stmp 发邮件的时候,即使用异步,也会比较卡(选用的邮件 ...

  10. 如何将SolidWorks文件另存为.obj文件及如何打开.obj格式文件

    原网站:http://fans.solidworks.com.cn/forum.php?mod=viewthread&tid=40238) OBJ文件是Alias Wavefront公司为它的 ...