加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

创建xml文件,添加节点,读取xml文件中某属性的属性值

发布时间:2020-12-16 05:02:09 所属栏目:百科 来源:网络整理
导读:using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq;//导入命名空间 using System.IO;//导入命名空间 namespace ClassLibrary1 { public class Book { public static XElement xml; public void
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;//导入命名空间
using System.IO;//导入命名空间

namespace ClassLibrary1
{
public class Book
{
public static XElement xml;
public void XmlBook(string Name,int Age,char Sex) {//

if (!File.Exists("xmlBooks.xml"))
{
//xml文件不存在,创建
xml = new XElement("Books");
xml.Save("xmlBooks.xml");
}
else {

//如果文件存在,就加载
xml = XElement.Load("xmlBooks.xml");

XElement ThingInfo=new XElement("book",//创建一个新节点,并为此节点添加子节点
new XAttribute("name",Name),//设置子节点的属性和属性值
new XAttribute("age",Age),
new XAttribute("sex",Sex)
);

xml.Add(ThingInfo);
xml.Save("xmlBooks.xml");//

}
}
public List<string> ReadxmlBook() {
xml = XElement.Load("xmlBooks.xml");//读xml文件的时候,需要先加载
List<string> BookInfo = new List<string>();
List<string> xmlBookInfo = xml.Elements("book")
.Select(n => n.Attribute("name").Value)//推论出name的属性值
.Distinct()//消除冗余项
.ToList();//转换成泛型集合
foreach (var item in xmlBookInfo)
{
BookInfo.Add(item);//添加到集合
}
return BookInfo;
}
}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读