您的位置:首页 > 其它

Linq to Xml

2016-06-03 17:48 323 查看

使用linq to xml 创建xml文件,查询xml文件中的信息

未完待续·····

生成的XML文件的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<Users>
<User ID="111111">
<name>EricSun</name>
<password>123456</password>
<description>Hello I'm from Dalian</description>
</User>
<User ID="222222">
<name>Ray</name>
<password>654321</password>
<description>Hello I'm from Jilin</description>
</User>
</Users>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Collections;

namespace ConsoleApplication6
{
class StudyXml
{
static void Main(string[] args)
{
string xmlpath = "Created.xml";
//第一个方法测试
// GenerateXmlFile(xmlpath);
//第二个方法测试
// GetXmlNodeInfo(xmlpath);
//第三个方法测试
GetNodeInfoLinq(xmlpath);
Console.ReadKey();
}
#region 生成一个xml文件
private static void GenerateXmlFile(string pathName)
{
try
{
XDocument xd = new XDocument(
new XElement("Users", new XElement("User", new XAttribute("ID", "111111"),
new XElement("name", "EricSun"),
new XElement("password", "123456"),
new XElement("description", "Hello I'm from Dalian")
),
//第三个
new XElement("User", new XAttribute("ID", "222222"),
new XElement("name", "Ray"),
new XElement("password", "654321"),
new XElement("description", "Hello I'm from Jilin")
)
)
);
xd.Save(pathName);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
#endregion

#region 如何获取xml中每个节点的信息
private static void GetXmlNodeInfo(string xmlpath)
{
//加载xml文件
XDocument document = XDocument.Load(xmlpath);
//获取“User”节点
XElement rootele =  document.Element("Users");
//遍历此节点下的属性和指定元素的值
foreach(XElement node in rootele.Elements("User"))
{
Console.WriteLine(node.Attribute("ID").Value);
string name = node.Element("name").Value;
string password = node.Element("password").Value;
string discription = node.Element("description").Value;
Console.WriteLine("{0}:{1}:{2}",name,password,discription);
}
}
#endregion

#region
private static void GetNodeInfoLinq(string path)
{
XDocument xdocument = XDocument.Load(path);
#region IEnumerable接口就一个方法,没有属性。
// GetEnumerator 返回一个循环访问集合的枚举数。 实现或继承了该接口,就是为了这个方法,可以foreach遍历。
#endregion
//查询元素名为name的值(xml中有两个元素的名都为name)
IEnumerable<XElement> ie = from nodes in xdocument.Descendants("name") select nodes;
foreach (XElement xd in ie)
{
Console.WriteLine(xd.Value);
}
IEnumerable<XElement> ie1 = from nodes1 in xdocument.Descendants("User")
where nodes1.Attribute("ID").Value.Equals("111111") &&
nodes1.HasElements
select nodes1;
foreach(XElement xe in ie1)
{
Console.WriteLine("this is the second");
Console.WriteLine(xe.Element("name").Value);
}
}
#endregion

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: