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. PyCharm创建文件时自动添加头注释

    进入设置 File->settings->Editor->File and Code Templates->Python Script 添加以下代码: #!/usr/bin/e ...

  2. MVC4的缓存

    目录(?)[+] MVC3缓存之一:使用页面缓存 在MVC3中要如果要启用页面缓存,在页面对应的Action前面加上一个OutputCache属性即可. 我们建一个Demo来测试一下,在此Demo中, ...

  3. 配置HADOOP_HOME

    配置HADOOP_HOME export HADOOP_HOME=/usr/hadoop-1.2.0export PATH=$PATH:$HADOOP_HOME/bin:$HADOOP_HOME/sb ...

  4. org.tmatesoft.svn.core.SVNCancelException: svn: E200015: authentication canc

    重新添加一个凭证,用新的凭证 第二总是取最新的代码,而不是用update 有问题,问哥

  5. IOS设计模式浅析之建造者模式(Builder)

    定义 "将一个复杂对象的构建与它的表现分离,使得同样的构建过程可以创建不同的表现". 最初的定义出现于<设计模式>(Addison-Wesley,1994). 看这个概 ...

  6. eclipse通过maven远程发布应用到Tomcat

    好久没有写博客了,今天为大家分享一下如何在eclipse通过maven远程发布应用到Tomcat. 一般情况下,我们发布应用到服务器需要现将应用导出成war包,然后连接服务器部署更新,这样是很耗时的, ...

  7. mysql 1005 错误

    建立外键的时候两个 表的相对应的 类型不一致!

  8. POJ 3480 &amp; HDU 1907 John(尼姆博弈变形)

    题目链接: PKU:http://poj.org/problem? id=3480 HDU:http://acm.hdu.edu.cn/showproblem.php? pid=1907 Descri ...

  9. SlidingMenu——使用前的配置

    一: 首先下载lib:SlidingMenu.然后将起导入eclipse中,然后将其clean一下,重新生成R文件. 二: 因为SlidingMenu依赖ActionBarSherlock,所以需要下 ...

  10. 【转】ATL提供的所有转换宏

    在头文件<atlconv.h>中定义了ATL提供的所有转换宏,如: A2CW (LPCSTR) -> (LPCWSTR) A2W     (LPCSTR) -> (LPWSTR ...