您的位置:首页 > 其它

.NET: XML

2015-07-08 13:56 405 查看
XML在平常生活中用得很多,它的结构很简单,跟windows explorer有点像。

对它进行操作主要有三种方式:XmlDocument,

假设有这么一个XML文件Book.XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleTest
{
public class Program
{
static private void showXmlInfoByLinq(string path)
{
XElement xe = XElement.Load(path);
IEnumerable<XElement> elements = from ele in xe.Elements("book")
select ele;
List<BookModel> modelList = new List<BookModel>();
foreach (var ele in elements)
{
BookModel model = new BookModel();
model.BookAuthor = ele.Element("author").Value;
model.BookName = ele.Element("title").Value;
model.BookPrice = Convert.ToDouble(ele.Element("price").Value);
model.BookISBN = ele.Attribute("ISBN").Value;
model.BookType = ele.Attribute("Type").Value;
modelList.Add(model);
}
foreach (BookModel book in modelList)
{
Console.WriteLine("Book ISBN: {0}   Type: {1}", book.BookISBN, book.BookType);
Console.WriteLine("\tBookName: {0}", book.BookName);
Console.WriteLine("\tBookAuthor: {0}", book.BookAuthor);
Console.WriteLine("\tBookPrice: {0}", book.BookPrice);
}
}

static void Main(string[] args)
{
const string PATH = @"C:\Users\Administrator\Desktop\Demo\Book.XML";

Console.WriteLine("\nRead by XmlLinq...\n");
showXmlInfoByLinq(PATH);

XElement xe = XElement.Load(PATH);
XElement record = new XElement(
new XElement("book",
new XAttribute("Type", "选修课"),
new XAttribute("ISBN", "7-111-19149-8"),
new XElement("title", "敏捷开发"),
new XElement("author", "秦朗"),
new XElement("price", 34.00)
)
);
xe.Add(record);
xe.Save(PATH);
Console.WriteLine("\nApending one child by XmlLinq...\n");
showXmlInfoByLinq(PATH);

xe = XElement.Load(PATH);
IEnumerable<XElement> element = from ele in xe.Elements("book")
where ele.Attribute("ISBN").Value == "7-111-19149-8"
select ele;
if (element.Count() > 0)
{
XElement first = element.First();
first.SetAttributeValue("Type", "必修课");
first.ReplaceNodes(
new XElement("title", "敏捷开发框架"),
new XElement("author", "秦明"),
new XElement("price", 35.00)
);
}
xe.Save(PATH);
Console.WriteLine("\nEditting one child by XmlLinq...\n");
showXmlInfoByLinq(PATH);

xe = XElement.Load(PATH);
IEnumerable<XElement> elements = from ele in xe.Elements("book")
where ele.Attribute("ISBN").Value == "7-111-19149-8"
select ele;
if (elements.Count() > 0)
{
elements.First().Remove();
}
xe.Save(PATH);
Console.WriteLine("\nRemoving one child by XmlLinq...\n");
showXmlInfoByLinq(PATH);
}
}
}


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