person.xml

<?xml version="1.0" encoding="utf-8"?>
<MyP>
<P1>
<Person id="cz001">
<Name>张三</Name>
<Age>18</Age>
</Person>
<Person id="cz002">
<Name>李四</Name>
<Age>19</Age>
</Person>
<Person id="cz003">
<Name>王五</Name>
<Age>20</Age>
</Person>
</P1>
<P2>
<Person>
<Name>张三2</Name>
<Age>18</Age>
</Person>
<Person>
<Name>李四2</Name>
<Age>19</Age>
</Person>
<Person>
<Name>王五2</Name>
<Age>20</Age>
</Person>
</P2>
</MyP>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace Xml操作
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
//读取XML
System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("person.xml");
System.Xml.Linq.XElement xeRoot = xdoc.Root; //根节点
System.Xml.Linq.XElement xele = xeRoot.Element("P1").Element("Person"); //子节点
MessageBox.Show("id=" + xele.Attribute("id").Value); //cz001
foreach (var ele in xele.Elements())
{
string str = string.Format("Name={0},Value={1}", ele.Name.ToString(), ele.Value);
MessageBox.Show(str);
}
} private void Form1_Load(object sender, EventArgs e)
{
//*读取XML数据加载到treeView1列表中。
//1、加载person.xml
System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("person.xml");
//2、获取根节点,MyP
System.Xml.Linq.XElement xeRoot = xdoc.Root;
//3、先把根节点添加到treeView1上
TreeNode treeViewRoot = treeView1.Nodes.Add(xeRoot.Name.LocalName);
//4、开始遍历所有的子节点,使用递归
LoadTreeNodes(xeRoot, treeViewRoot); //*写入XML文件。
//1、创建XML对象
System.Xml.Linq.XDocument xdocument = new System.Xml.Linq.XDocument();
//2、创建跟节点
System.Xml.Linq.XElement eRoot = new System.Xml.Linq.XElement("根节点");
//添加到xdoc中
xdocument.Add(eRoot);
//3、添加子节点
System.Xml.Linq.XElement ele1 = new System.Xml.Linq.XElement("子节点1");
ele1.Value = "内容1";
eRoot.Add(ele1);
//4、为ele1节点添加属性
System.Xml.Linq.XAttribute attr = new System.Xml.Linq.XAttribute("url", "http://www.baidu.com");
ele1.Add(attr); //5、快速添加子节点方法
eRoot.SetElementValue("子节点2", "内容2"); //6、快速添加属性
ele1.SetAttributeValue("id", ); //7、最后保存到文件,也可以写入到流中。
xdocument.Save("123.xml"); } private void LoadTreeNodes(System.Xml.Linq.XElement xeRoot, TreeNode treeViewRoot)
{
//把xeRoot下面的所有内容循环绑定treeView上
foreach (System.Xml.Linq.XElement ele in xeRoot.Elements())
{
//判定子根节点下是否还有子节点
if (ele.Elements().Count() > )
{
TreeNode node = treeViewRoot.Nodes.Add(ele.Name.ToString()); //写入Name值
//获取节点上的属性方法
System.Xml.Linq.XAttribute attr = ele.Attribute("id");
if (attr != null)
{
node.Text += string.Format(" [{0}={1}]", attr.Name, attr.Value);
}
LoadTreeNodes(ele, node); //遍历循环
}
else
{
treeViewRoot.Nodes.Add(ele.Value); //写入节点下的Value
}
}
}
}
}

重新学习xml操作和xml序列化

1、先了解下xml格式,并手动创建xml文件。

1、XML只能有一个根节点。
 2、XML有开始标记就必须有结束标记。
 3、XML元素的属性值必须有引号。
 4、XML必须有结束标记,大小写必须跟开始标记一致。
 5、XML文件编码必须跟encoding指定编码要一致。

123.xml文件:

<?xml version="1.0" encoding="utf-8" ?>
<hgx>
<P1>
<Person ID="h001">
<Name>张三</Name>
<Age>18</Age>
</Person>
<Person ID="h002">
<Name>李四</Name>
<Age>20</Age>
</Person>
</P1>
<P2>
<Person ID="h003">
<Name>王五</Name>
<Age>21</Age>
</Person>
<Person ID="h004">
<Name>赵六</Name>
<Age>25</Age>
</Person>
</P2>
</hgx>

2、通过XDocument类访问读取xml文件。

static void Main(string[] args)
{
XDocument xDoc = XDocument.Load("123.xml"); //加载xml文件
XElement root = xDoc.Root; //获取根节点 //通过递归,获取所有下面的子元素
GetXElement(root);
Console.ReadKey();
} private static void GetXElement(XElement root)
{
//返回IEnumerable接口的对象,都可以实现foreach循环遍历
foreach (XElement element in root.Elements())
{
//递归
if (element.Elements().Count() > )
{
Console.WriteLine(element.Name);
GetXElement(element);
}
else
{
Console.WriteLine(element.Value);
}
}
}

3、将123.xml文件内容加载到TreeView控件中显示。

private void button1_Click(object sender, EventArgs e)
{
XDocument xDoc = XDocument.Load("123.xml");
XElement root = xDoc.Root; //获取根元素
TreeNode treeNode = this.treeView1.Nodes.Add(root.Name.ToString());
LoadNodes(root, treeNode);
} private void LoadNodes(XElement root, TreeNode treeNode)
{
foreach (XElement element in root.Elements())
{
if (element.Elements().Count() > )
{
TreeNode node = treeNode.Nodes.Add(element.Name.ToString());
//获取属性
foreach (XAttribute attr in element.Attributes())
{
node.Text += " [" + attr.Name.ToString() + "=" + attr.Value + "]";
}
LoadNodes(element, node);
}
else
{
TreeNode node = treeNode.Nodes.Add(element.Value);
}
}
}

4、写入xml操作

private void button2_Click(object sender, EventArgs e)
{
//创建XML对象
XDocument xDoc = new XDocument();
//创建一个根节点
XElement root = new XElement("Root");
xDoc.Add(root); //将根节点加入到XML对象中
//创建一个子节点
XElement xele = new XElement("User");
root.Add(xele);
//添加属性
XAttribute attr = new XAttribute("ID", );
xele.Add(attr);
xele.SetElementValue("Name", "张三");
xele.SetElementValue("Age", ""); //保存xml文件
xDoc.Save("User.xml");
}

User.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<Root>
<User ID="1">
<Name>张三</Name>
<Age>18</Age>
</User>
</Root>

5、xml序列化和反序列化操作

Person类:

public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; } [XmlIgnore] //此属性不被序列化,System.Xml.Serialization.XmlIgnoreAttribute
public bool Gender { get; set; }
}

xml序列化:

private void button3_Click(object sender, EventArgs e)
{
List<Person> list = new List<Person>();
Person p1 = new Person() { ID = , Name = "张三", Age = };
Person p2 = new Person() { ID = , Name = "李四", Age = };
list.Add(p1);
list.Add(p2); //xml序列化,System.Xml.Serialization.XmlSerializer
XmlSerializer xmlSer = new XmlSerializer(typeof(List<Person>));
using (System.IO.FileStream fs = System.IO.File.OpenWrite("Person.xml"))
{
xmlSer.Serialize(fs, list);
}
}

Person.xml文件:

<?xml version="1.0"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<ID>1</ID>
<Name>张三</Name>
<Age>18</Age>
</Person>
<Person>
<ID>2</ID>
<Name>李四</Name>
<Age>20</Age>
</Person>
</ArrayOfPerson>

xml反序列化:

private void button4_Click(object sender, EventArgs e)
{
List<Person> list = new List<Person>();
//xml反序列化
XmlSerializer xmlSer = new XmlSerializer(typeof(List<Person>));
using (System.IO.FileStream fs = System.IO.File.OpenRead("Person.xml"))
{
list = (List<Person>)xmlSer.Deserialize(fs);
} foreach (Person p in list)
{
MessageBox.Show(string.Format("ID:{0},Name:{1},Age:{2}", p.ID, p.Name, p.Age));
}
}

C# Xml Linq XDocument 基本操作 -- 重新学习的更多相关文章

  1. LINQ to XML LINQ学习第一篇

    LINQ to XML LINQ学习第一篇 1.LINQ to XML类 以下的代码演示了如何使用LINQ to XML来快速创建一个xml: public static void CreateDoc ...

  2. Linq查询基本操作

    摘要:本文介绍Linq查询基本操作(查询关键字) - from 子句 - where 子句 - select子句 - group 子句 - into 子句 - orderby 子句 - join 子句 ...

  3. C#中Linq查询基本操作

    摘要:本文介绍Linq查询基本操作(查询关键字) - from 子句 - where 子句 - select子句 - group 子句 - into 子句 - orderby 子句 - join 子句 ...

  4. xml解析与生成的学习资料

    xml解析与生成的学习资料:http://blog.csdn.net/u012325167/article/category/6129813 ----------------------------- ...

  5. 应用Xml.Linq读xml文件

    c#提供了System.Xml.Linq操作xml文件,非常方便,本文主要介绍如何应用System.Xml.Linq读取xml文件. xml文本 <?xml version="1.0& ...

  6. 【总结】LINQ查询基本操作列表

    每个LINQ查询都以from子句开始,from子句包括以下两个功能. 指定查询将采用数据源. 定义一个本地变量,表示数据源中单个元素. string[] values = { "中国&quo ...

  7. XML Linq 学习笔记

    XML如下: <?xml version="1.0" encoding="utf-8"?> <Dishes> <Dish> ...

  8. xml linq

    这里讲解一下linq对xml的基本操作,包括: 新建xml.新建节点 查询节点 插入属性.插入节点 替换节点 在这里我封装了一些常用的方法: public class XmlHelper { /// ...

  9. Linq查询操作语句学习

    对于一个集合,我们通常会用foreach或者for循环来判断查找里面的元素. 但这种方法通常会看起来比较复杂,我们可以使用linq. Linq允许编写C#代码以查询数据库相同的方式操作内存数据(写法类 ...

随机推荐

  1. Charles 的几个调试技巧

    Charles 是一个网络调试的代理工具,类似 Windows 下的 Fildder,这里介绍下几个常用的调试技巧,使用的版本是 Charles 4. 1.移动端抓包 在移动开发中,经常会遇到在手机上 ...

  2. UITabelViewFootView(转)

    在处理UITableView表格时,我们希望在View底部添加按钮. 用户拖动UITableView时按钮能跟随移动. 如题,实现如下界面: - (CGFloat)tableView:(UITable ...

  3. SHELL $RANDOM产生的随机数范围是0到32767

    1.使用系统的 $RANDOM 变量 fdipzone@ubuntu:~$ echo $RANDOM 17617 fdipzone@ubuntu:~$ echo $RANDOM 17617 $RAND ...

  4. Xshell配色方案(Solarized Dark)

    将以下内容复制并保存到文件中,文件名以xc为后缀,如:Solarized Dark.xcs [Solarized Dark] text= cyan(bold)=93a1a1 text(bold)= m ...

  5. redhat ent 6.5 virtualbox虚拟机通过桥接方式配置主机-虚拟机的局域网

    感谢: http://www.linuxidc.com/Linux/2012-06/62544.htm http://www.2cto.com/os/201204/126178.html Virual ...

  6. phpcs,phpmd,phan安装部署,phpstorm配置phpunit

    git参考地址:https://github.com/YunhanTech/overview/blob/master/php/learn-road.md phpcs 安装 composer globa ...

  7. 机器学习之猫狗大战,解决image RGB values must be in the 0..1 range.

    猫狗大战是比较经典的机器学习案例,前几天体验了一番,来记录一下 1.图片准备 首先是准备训练的图片 链接:https://pan.baidu.com/s/1ht1HIuw 密码:aw9s 2.开始训练 ...

  8. ubuntu 16.04 系统语言汉化

    转载自:https://jingyan.baidu.com/article/5553fa82cedaa265a2393420.html

  9. MVC架构模式概述

    MVC MVC概述: Model–view–controller (MVC) is a software architectural pattern for implementing user int ...

  10. 《UNIX网络编程》 -- 第五章

    str_cli 和 str_echo 函数 需要先弄清楚 3.9 readn.writen 和 readline 函数 str_cli void str_cli(FILE *fp, int sockf ...