引言:在实际项目中遇到一些关于xml操作的问题,被逼到无路可退的时候终于决定好好研究xml一番。本文首先介绍了xml的基本操作,后面写了一个经常用到的xml保存配置文件的实例。

xml常用方法:

定义xml文档:XmlDocument xmlDoc = new XmlDocument();

初始化xml文档:xmlDoc.Load("D:\\book.xml");//找到xml文件

创建根元素:XmlElement xmlElement = xmlDoc.CreateElement("", "Employees", "");

创建节点:XmlElement xeSub1 = xmlDoc.CreateElement("title");

查找Employees节点:XmlNode root = xmlDoc.SelectSingleNode("Employees");

添加节点:xe1.AppendChild(xeSub1);

更改节点的属性:xe.SetAttribute("Name", "李明明");

移除xe的ID属性:xe.RemoveAttribute("ID");

删除节点title:xe.RemoveChild(xe2);

1 创建xml文档

因为比较简单,直接写方法及结果。

public void CreateXMLDocument()
        {
            XmlDocument xmlDoc = new XmlDocument();

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

//加入Employees根元素
            XmlElement xmlElement = xmlDoc.CreateElement("", "Employees", "");
            xmlDoc.AppendChild(xmlElement);

//添加节点
            XmlNode root = xmlDoc.SelectSingleNode("Employees");
            XmlElement xe1 = xmlDoc.CreateElement("Node");
            xe1.SetAttribute("Name", "李明");
            xe1.SetAttribute("ISB", "2-3631-4");

//添加子节点
            XmlElement xeSub1 = xmlDoc.CreateElement("title");
            xeSub1.InnerText = "学习VS";
            xe1.AppendChild(xeSub1);

XmlElement xeSub2 = xmlDoc.CreateElement("price");
            xe1.AppendChild(xeSub2);
            XmlElement xeSub3 = xmlDoc.CreateElement("weight");
            xeSub3.InnerText = "20";
            xeSub2.AppendChild(xeSub3);

root.AppendChild(xe1);
            xmlDoc.Save("D:\\book.xml");//保存的路径
        }

结果:

<?xml version="1.0" encoding="GB2312"?>
-<Employees>-

  <Node ISB="2-3631-4" Name="李明">

    <title>学习VS</title>-

    <price>

      <weight>20</weight>

    </price>

  </Node>

</Employees>

2 增加节点

XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("D:\\book.xml");//找到xml文件
            XmlNode root = xmlDoc.SelectSingleNode("Employees");//查找Employees节点
            XmlElement xe1 = xmlDoc.CreateElement("Node2");//添加Node2节点
            xe1.SetAttribute("Name", "张三");
            XmlElement xeSub1 = xmlDoc.CreateElement("title");//定义子节点
            xeSub1.InnerText = "心情好";
            xe1.AppendChild(xeSub1);//添加节点到Node2
            root.AppendChild(xe1);//添加节点到Employees
            xmlDoc.Save("D:\\book.xml");

结果:

<?xml version="1.0" encoding="GB2312"?>
  -<Employees>

    -<Node ISB="2-3631-4" Name="李明">

      <title>学习VS</title>-

      <price>

        <weight>20</weight>

      </price>

    </Node>-

    <Node2 Name="张三">

      <title>心情好</title>

    </Node2>-

    <Node2 Name="张三">

      <title>心情好</title>

    </Node2>

</Employees>

3 修改节点:

public void ModifyNode()
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("D:\\book.xml");
XmlNodeList nodeList = xmlDocument.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点
foreach (XmlNode xn in nodeList)//遍历
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("Name") == "李明")
{
xe.SetAttribute("Name", "李明明");//更改节点的属性
XmlNodeList xnl = xe.ChildNodes;//获取xe的所有子节点
foreach (XmlNode xn1 in xnl)
{
XmlElement xe2 = (XmlElement)xn1;//将节点xn1的属性转换为XmlElement
if (xe2.Name == "title")//找到节点名字为title的节点
{
xe2.InnerText = "今天天气不好";
}
if (xe2.Name == "price")
{
XmlNodeList xnl2 = xe2.ChildNodes;
foreach (XmlNode xn2 in xnl2)
{
if (xn2.Name == "weight")
{
xn2.InnerText = "88";
}
}
}
}
}
}
xmlDocument.Save("D:\\book2.xml");
}
result:
<?xml version="1.0" encoding="GB2312"?>
-<Employees>
-<Node ISB="2-3631-4" Name="李明明">
<title>今天天气不好</title>-<price>
<weight>88</weight>
</price>
</Node>
-<Node2 Name="张三">
<title>心情好</title>
</Node2></Employees>
 

4 删除节点:

public void ModifyNode()
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("D:\\book.xml");
XmlNodeList nodeList = xmlDocument.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点
foreach (XmlNode xn in nodeList)//遍历
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("Name") == "李明")
{
xe.SetAttribute("Name", "李明明");//更改节点的属性
XmlNodeList xnl = xe.ChildNodes;//获取xe的所有子节点
foreach (XmlNode xn1 in xnl)
{
XmlElement xe2 = (XmlElement)xn1;//将节点xn1的属性转换为XmlElement
if (xe2.Name == "title")//找到节点名字为title的节点
{
xe2.InnerText = "今天天气不好";
}
if (xe2.Name == "price")
{
XmlNodeList xnl2 = xe2.ChildNodes;
foreach (XmlNode xn2 in xnl2)
{
if (xn2.Name == "weight")
{
xn2.InnerText = "88";
}
}
}
}
}
}
xmlDocument.Save("D:\\book2.xml");
}
result:
<?xml version="1.0" encoding="GB2312"?>
-<Employees>
-<Node ISB="2-3631-4" Name="李明明">
<title>今天天气不好</title>-<price>
<weight>88</weight>
</price>
</Node>
-<Node2 Name="张三">
<title>心情好</title>
</Node2></Employees>

前面介绍了xml的创建、节点的添加、节点的修改和删除,下面以写的一个保存项目配置文件的小例子。

举例说明:

首先在项目文件中创建一个xml文档:

<?xml version="1.0" encoding="utf-8" ?>
<configurationN>
    <ServerAddress>1143</ServerAddress>
    <ID>192.168</ID>
  </configurationN>

在保存配置文件时,最主要使用了两个方法:Load和Save。

Load:初始化xml文档,以便项目文件获取具体的xml节点的值。

public void Load(string path)
{
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;
foreach (XmlNode xn in xnl)
{
if (xn.Name == configuration_ServerAddress)
{
ServerAddress = xn.InnerText;
}
}
}
catch(Exception ex)
{ }
}

Save:在项目系统中进行修改配置文件值后,需要对xml进行重新保存

public void Save(string path)
{
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;
foreach (XmlNode xn in xnl)
{
if (xn.Name == configuration_ServerAddress)
{
xn.InnerText = ServerAddress;
}
} xmlDocument.Save(path);
}
catch (Exception ex)
{ }
}

此处将所有代码都贴出来,方便下次实现。因为项目是WPF文件,而且都是简单控件,所以只贴出后台代码。

class ConfigurationManager:INotifyPropertyChanged
{
public const string managerNode = "configurationN";//根节点
public const string configuration_ServerAddress = "ServerAddress";//子节点 private string _ServerAddress;
public string ServerAddress
{
get { return _ServerAddress; }
set
{
_ServerAddress = value;
NotifyPropertyChanged("ServerAddress");
}
} public void Load(string path)
{
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;
foreach (XmlNode xn in xnl)
{
if (xn.Name == configuration_ServerAddress)
{
ServerAddress = xn.InnerText;
}
}
}
catch(Exception ex)
{ }
} public void Save(string path)
{
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;
foreach (XmlNode xn in xnl)
{
if (xn.Name == configuration_ServerAddress)
{
xn.InnerText = ServerAddress;
}
} xmlDocument.Save(path);
}
catch (Exception ex)
{ }
} public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
} public static ConfigurationManager Instance = new ConfigurationManager();
} public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Start();
this.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString(); }
private string path = "CONFIG\\System.xml"; private void button1_Click(object sender, RoutedEventArgs e)
{
ConfigurationManager.Instance.ServerAddress = this.tb1.Text;
ConfigurationManager.Instance.Save(path);
} private void button2_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
} private void Start()
{
ConfigurationManager.Instance.Load(path);
}
}
class ConfigurationManager:INotifyPropertyChanged
{
public const string managerNode = "configurationN";//根节点
public const string configuration_ServerAddress = "ServerAddress";//子节点 private string _ServerAddress;
public string ServerAddress
{
get { return _ServerAddress; }
set
{
_ServerAddress = value;
NotifyPropertyChanged("ServerAddress");
}
} public void Load(string path)
{
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;
foreach (XmlNode xn in xnl)
{
if (xn.Name == configuration_ServerAddress)
{
ServerAddress = xn.InnerText;
}
}
}
catch(Exception ex)
{ }
} public void Save(string path)
{
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(path); XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;
foreach (XmlNode xn in xnl)
{
if (xn.Name == configuration_ServerAddress)
{
xn.InnerText = ServerAddress;
}
} xmlDocument.Save(path);
}
catch (Exception ex)
{ }
} public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
} public static ConfigurationManager Instance = new ConfigurationManager();
} public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Start();
this.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString(); }
private string path = "CONFIG\\System.xml"; private void button1_Click(object sender, RoutedEventArgs e)
{
ConfigurationManager.Instance.ServerAddress = this.tb1.Text;
ConfigurationManager.Instance.Save(path);
} private void button2_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
} private void Start()
{
ConfigurationManager.Instance.Load(path);
}
}

xml基本操作和保存配置文件应用实例的更多相关文章

  1. xml基本操作

    在实际项目中遇到一些关于xml操作的问题,被逼到无路可退的时候终于决定好好研究xml一番.xml是一种可扩展标记语言,可跨平台进行传输,因此xml被广泛的使用在很多地方. 本文由浅入深,首先就xml的 ...

  2. Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 一.前言 我们在<中我们描述了Python数据持久化的大体概念和基本处理方式,通过这些知识点我们已经 ...

  3. 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    [转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...

  4. 【Android】11.2 通过重写对应的方法保存和恢复实例的状态

    分类:C#.Android.VS2015: 创建日期:2016-02-21 一.简介 通过重写(也叫回调)对应的方法来管理Activity的生命周期,比如用户旋转屏幕时应用程序要能自动保存和恢复实例的 ...

  5. 【C#】Config配置文件的读写,及无法写入/保存配置文件的问题

    目的: 一些数据为了在项目打包好后也能方便的修改和调用,通常会把这些数据放到配置文件中,避免硬编码,修改配置文件内容更方便,而不用修改源代码. 使用: 在解决方案资源管理器中找到App.config文 ...

  6. WPF 分享一种设置程序保存配置文件的方法

    最近需要做一个配置程序,主要给其他程序做相关配置的小工具. 配置项蛮多的,一般我们都是将各个配置项写到配置文件的节点中,比如App.config文件或者自定义的xml文件. 因为我用的是wpf,MVV ...

  7. 读取xml文件中的配置参数实例_java - JAVA

    文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 paras.xml文件 <?xml version="1.0" encoding=" ...

  8. boost::xml——基本操作以及中文乱码解决方案

    下面是本人使用boost库的xml部分的基础操作,并且解决对于大家使用boost库读写中文xml内容出现的乱码问题. 1.实现boost库xml基本操作2.解决boost对xml中中文乱码问题3.实现 ...

  9. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener

    一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...

随机推荐

  1. 解决eclipse manven项目添加不了maven dependencis

    <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"& ...

  2. spring中scope作用域(转)

    今天研究了一下scope的作用域.默认是单例模式,即scope="singleton".另外scope还有prototype.request.session.global sess ...

  3. mybatis 学习!

    参考链接 http://www.mybatis.org/spring/zh/mappers.html http://www.cnblogs.com/fangjian0423/p/spring-myba ...

  4. ViewPager部分源码分析二:FragmentManager对Fragment状态的管理完成ViewPager的child添加或移出

    ViewPager维护child代码流程: 注:PagerAdapter 使用的是FragmentPagerAdapter类或者它的子类. viewPager.populate(): void pop ...

  5. ListView + PopupWindow实现滑动删除

    原文:ListView滑动删除 ,仿腾讯QQ(鸿洋_) 文章实现的功能是:在ListView的Item上从右向左滑时,出现删除按钮,点击删除按钮把Item删除. 看过文章后,感觉没有必要把dispat ...

  6. Jquery.Datatables dom表格定位

    Datatables会添加一些控制元素在表格的周围,比如默认状态下改变每页显示条数(l)的空间在左上角,即使搜索框(f)在右上角,表格的信息(i)显示在左下角,分页控件(p)显示在右下角. 这些控件在 ...

  7. 【翻译二十】-java线程池

    Thread Pools Most of the executor implementations in java.util.concurrent use thread pools, which co ...

  8. git 打标签并推送tag到托管服务器

    我们常常在代码封板时,使用git 创建一个tag ,这样一个不可修改的历史代码版本就像被我们封存起来一样,不论是运维发布拉取,或者以后的代码版本管理,都是十分方便的. 首先我们了解下 git 的 ta ...

  9. 手机WebAPP设计注意事项和解决方法

    1. 基本手机网页设计 1.1 wap端的网站表头 wap端的网站,写的时候首先注意表头,因为是手机端的,所以和我们平常用的web端页面的不一样,表头为: 1.2 尽量少使用水平滚动. 水平滚动除了比 ...

  10. C#从Image上读取文本

    今天通过C#来实现一个读取Image上文本的功能. 1. 环境准备: 1). 下载 Microsoft Office SharePoint Designer 2007. 2). 安装请参考KB:htt ...