C#操作XML文件示例
一.首先在项目中创建一个Book.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<!--记录书本的信息-->
<book Type="必修课" ISBN="7-111-19149-2">
<title>数据结构</title>
<author>严蔚敏</author>
<price>30.00</price>
</book>
<book Type="必修课" ISBN="7-111-19149-3">
<title>路由型与交换型互联网基础</title>
<author>程庆梅</author>
<price>27.00</price>
</book>
<book Type="必修课" ISBN="7-111-19149-4">
<title>计算机硬件技术基础</title>
<author>李继灿</author>
<price>25.00</price>
</book>
<book Type="必修课" ISBN="7-111-19149-5">
<title>软件质量保证与管理</title>
<author>朱少民</author>
<price>39.00</price>
</book>
<book Type="必修课" ISBN="7-111-19149-6">
<title>算法设计与分析</title>
<author>王红梅</author>
<price>23.00</price>
</book>
<book Type="选修课" ISBN="7-111-19149-1">
<title>计算机操作系统</title>
<author>7-111-19149-1</author>
<price>28</price>
</book>
</bookstore>
二.为了读取方便,我们再创建一个实体类BookModel与之对应,代码如下:
public class BookModel
{
public BookModel()
{ }
/// <summary>
/// 所对应的课程类型
/// </summary>
private string bookType;
public string BookType
{
get { return bookType; }
set { bookType = value; }
}
/// <summary>
/// 书所对应的ISBN号
/// </summary>
private string bookISBN;
public string BookISBN
{
get { return bookISBN; }
set { bookISBN = value; }
}
/// <summary>
/// 书名
/// </summary>
private string bookName;
public string BookName
{
get { return bookName; }
set { bookName = value; }
}
/// <summary>
/// 作者
/// </summary>
private string bookAuthor;
public string BookAuthor
{
get { return bookAuthor; }
set { bookAuthor = value; }
}
/// <summary>
/// 价格
/// </summary>
private double bookPrice;
public double BookPrice
{
get { return bookPrice; }
set { bookPrice = value; }
}
}
3.操作xml文件的代码如下:
List<BookModel> bookModeList = new List<BookModel>();
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;//忽略文档里面的注释,因为在没有特别说明的情况下,注释也是一个节点
XmlReader reader = XmlReader.Create(@"..\..\Book.xml", settings);
doc.Load(reader);
XmlNode xn = doc.SelectSingleNode("bookstore");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xn1 in xnl)
{
BookModel bookModel = new BookModel();
// 将节点转换为元素,便于得到节点的属性值
XmlElement xe = (XmlElement)xn1;
// 得到Type和ISBN两个属性的属性值
bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
bookModel.BookType = xe.GetAttribute("Type").ToString();
// 得到Book节点的所有子节点
XmlNodeList xnl0 = xe.ChildNodes;
bookModel.BookName = xnl0.Item(0).InnerText;
bookModel.BookAuthor = xnl0.Item(1).InnerText;
bookModel.BookPrice = Convert.ToDouble(xnl0.Item(2).InnerText);
bookModeList.Add(bookModel);
}
reader.Close();//读取完毕后,记得要关掉reader
foreach(BookModel bm in bookModeList)
{
Console.WriteLine(bm.BookName + "\r\n");
Console.WriteLine(bm.BookAuthor + "\r\n");
Console.WriteLine(bm.BookPrice + "\r\n");
}
Console.ReadKey();
运行效果:
另:
如果将Book.xml文件属性设置成嵌入的资源,则读取xml的代码为:
string name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Book.xml";
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
using (System.IO.Stream s = assembly.GetManifestResourceStream(name))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
using (XmlReader reader = XmlReader.Create(s,settings))
{
List<BookModel> bookModeList = new List<BookModel>();
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNode xn = doc.SelectSingleNode("bookstore");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xn1 in xnl)
{
BookModel bookModel = new BookModel();
// 将节点转换为元素,便于得到节点的属性值
XmlElement xe = (XmlElement)xn1;
// 得到Type和ISBN两个属性的属性值
bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
bookModel.BookType = xe.GetAttribute("Type").ToString();
// 得到Book节点的所有子节点
XmlNodeList xnl0 = xe.ChildNodes;
bookModel.BookName = xnl0.Item(0).InnerText;
bookModel.BookAuthor = xnl0.Item(1).InnerText;
bookModel.BookPrice = Convert.ToDouble(xnl0.Item(2).InnerText);
bookModeList.Add(bookModel);
}
reader.Close();
foreach (BookModel bm in bookModeList)
{
Console.WriteLine(bm.BookName + "\r\n");
Console.WriteLine(bm.BookAuthor + "\r\n");
Console.WriteLine(bm.BookPrice + "\r\n");
}
//Console.ReadKey();
}
}
另一种方法:
XmlDocument xmlDoc = new XmlDocument();
//创建Xml声明部分,即<?xml version="1.0" encoding="utf-8" ?>
XmlDeclaration Declaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
//创建根节点
XmlNode rootNode = xmlDoc.CreateElement("root");
//创建student子节点
XmlNode testPointNode = xmlDoc.CreateElement("testPoint");
//创建一个属性
XmlAttribute testPointID = xmlDoc.CreateAttribute("TestPointID");
testPointID.Value = "1";
XmlAttribute caseID = xmlDoc.CreateAttribute("CaseId");
caseID.Value = "TEST_0001";
XmlAttribute name = xmlDoc.CreateAttribute("Name");
name.Value = "111";
//xml节点附件属性
testPointNode.Attributes.Append(testPointID);
testPointNode.Attributes.Append(caseID);
testPointNode.Attributes.Append(name);
rootNode.AppendChild(testPointNode);
//附加根节点
xmlDoc.AppendChild(rootNode);
xmlDoc.InsertBefore(Declaration, xmlDoc.DocumentElement);
//保存Xml文档
xmlDoc.Save(@"d:\testPoint.xml");