是一种文本文件格式,由:标签和属性组成元素(节点),由元素组成“树状结构”
复习:html (html5 vs xhtml)
比HTML更严格:
被设计用来传输和存储数据(竞争对手:Json)
其他:
XML文件生成和加载
理解:
XElement luckystack = new XElement(
"luckystack", //节点名称
new XComment("源栈欢迎您!"), //注释
new XElement("location", "CQ", //location为节点名称,CQ为值
new XAttribute("head", true)), //元素属性
new XElement("teachers",
new XElement("name", "大飞哥",
//一个元素可以有多个=属性
new XAttribute("position", "head"),
new XAttribute("age", 1)),
new XElement("name", "小鱼", new XAttribute("position", "UI")),
//元素也可以没有属性
new XElement("name", "阿杰")
)
);
Console.WriteLine(luckystack);
演示(复习):
生成XML文件:
XDocument document = new XDocument(
new XDeclaration("1.0", "utf-8","yes"), //添加一个XML声明
luckystack);
document.Save("C:\\17bang\\luckystack.xml");
看一看XML的继承关系:XObject
XML声明只能在文件中才能显示,为什么?(源代码查找演示)
ws.OmitXmlDeclaration = true;
程序员尤其需要“自学”能力!如果什么都要飞哥给你讲了你才会,那飞哥得给你讲十年……但十年之后飞哥给你讲的技术又特么过时了!培训班,只能是一个“师傅领进门”的过程。
加载XML文件:
XElement element = XElement.Load("C:\\17bang\\luckystack.xml");
XML操作
查:其实是最核心的内容,因为实现要找到进行操作的对象或位置简单查找可直接使用XNode及其子类的自有属性:
Console.WriteLine(
//element
//element.FirstNode
//element.Element("teachers")
element.Element("teachers").FirstNode
((XElement)element.Element("teachers").FirstNode).Attribute("position"));
复杂查找推荐使用Linq to XML,其实上述XML的生成和加载都是Linq to XML的一部分(都在System.Xml.Linq名称空间下)。
var teachers = from x in element.Descendants()
//where x.Name == "name" //可以多个where一起使用
//where x.Value.Contains("飞哥") //特别注意使用Value进行查询得到的结果
//where !x.HasAttributes
where (string)x.Attribute("position") == "UI" //为什么这里可以使用(string)进行强制转换?
//where x.Attribute("position").ToString() == "UI" //如果用ToString()会发生什么?
select x;
在Linq的查询结果中进行增删操作:
IList<XElement> lstTeachers = teachers.ToList();
//foreach (var item in teachers)
foreach (var item in lstTeachers) //区别在哪?
{
//这是否违法了foreach“只读”的规则?
//item = new XElement();
item.Remove();
}
用ToList()和不用ToList()的区别,复习:
衡量一个程序员的水平,除了看他能写出什么样的代码,还可以看他能读懂什么样的代码!
读代码比写代码更难,同学们要有意识的练习阅读源代码的能力,还有查看异常信息的能力……
作业:
---------------------------
基础
---------------------------
<articles>
<!-- 以下存放所有“源栈”所有文章 -->
<article isDraft="false">
<id>1</id>
<title>源栈培训:C#进阶-7:Linq to XML</title>
<body>什么是XML(EXtensible Markup Language)是一种文本文件格式被设计用来传输和存储数据由:标签和属性组成元素(节点),由元素组成“树状结构”必须有而且只能有一个根节点其他: </body>
<authorId>1</authorId>
<publishDate>2019/6/18 18:15</publishDate>
<comments>
<comment recommend="true">
<id>12</id>
<body>不错,赞!</body>
<authorId>2</authorId>
</comment>
<comment>
<id>14</id>
<body>作业太难了</body>
<authorId>3</authorId>
</comment>
</comments>
</article>
<article isDraft="true">
<id>2</id>
<title>源栈培训:C#进阶-6:异步和并行</title>
<authorId>1</authorId>
</article>
</articles>
---------------------------
进阶
---------------------------
---------------------------
高级
---------------------------
作业点评:
多快好省!前端后端,线上线下,名师精讲
更多了解 加: