[传智播客学习日记]C#中的常用XML函数总结(读XML)

读取XML文档内信息的操作与写操作类似,首先要加载一个XML文件成为一个可操纵的对象。

假设我们有个XML文件叫student.xml。

1 XDocument xDoc = XDocument.Load("students.xml");

之后要获取根节点

1 XElement xeRoot = xDoc.Root;

如果我们想取得某一节点的话:

1 //根据标签名获取某一个节点
2 XElement xe1 = xeRoot.Element("标签名");
3 //输出节点名
4 Console.WriteLine(xe1.Name);
5 //输出节点下所有元素的值
6 Console.WriteLine(xe1.Value);

如果我们想取得某节点下整个一层子节点的话:

1 //这里获得xeRoot下一层的子节点集合
2 foreach (XElement item in xeRoot.Elements())
3 {
4 Console.WriteLine(item.Name);
5 }

如果我们希望取得所有节点,由于XML是层次结构的,就需要用递归遍历了,可以使用一个递归函数:

1 static void Recursion(XElement root)
2 {
3 foreach (XElement item in root.Elements())
4 {
5 Console.WriteLine(item.Name);
6 Recursion(item);
7 }
8 }

如果想取得一个元素item的某个属性的值,可以这样:

1 //获取某一属性
2 XAttribute attr = item.Attribute("属性名");
3 //输出属性值
4 Console.WriteLine(attr.Value);






你可能感兴趣的:(xml)