您的位置:首页 > 编程语言 > C#

C#XML文件操作工具类

2018-02-08 14:34 567 查看
分享一个博主自己写的XML文件操作的基本工具类:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace ClassLibrary1
{
public class xml
{
/// <summary>
/// 生成xml 文件
/// </summary>
/// <param name="xmlpath">路径</param>
public void CreateXml(string xmlpath)
{
//创建XML 格式
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();
}

/// <summary>
/// 添加节点or属性
/// </summary>
/// <param name="xmlPath">路径</param>
public void Add(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);

var root = xmlDoc.DocumentElement;//取到根结点

#region 添加节点
//添加节点:其中-NewBook- 是节点名称
XmlNode newNode = xmlDoc.CreateNode("element", "NewBook", "");
newNode.InnerText = "WPF";
//添加为根元素的第一层子结点
root.AppendChild(newNode);
#endregion

#region 添加属性
//添加属性
XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
node.SetAttribute("Name", "WPF");
#endregion

xmlDoc.Save(xmlPath);
}

/// <summary>
/// 删除节点or属性
/// </summary>
/// <param name="xmlPath">路径</param>
public void Delete(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
var root = xmlDoc.DocumentElement;//取到根结点

var element = xmlDoc.SelectSingleNode("BookStore/Book");

//移除指定属性
root.RemoveAttribute("Name");
xmlDoc.Save(xmlPath);

//移除节点
root.RemoveChild(element);

//移除当前节点所有属性,不包括默认属性
//node.RemoveAllAttributes();

xmlDoc.Save(xmlPath);
}

/// <summary>
/// 修改属性(xml节点是只读的,默认不可修改)
/// </summary>
/// <param name="xmlPath">路径</param>
public void Update(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);

XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");

element.SetAttribute("Name", "Zhang");

xmlDoc.Save(xmlPath);
}
}
}

使用的时候直接调取fangf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: