WPF 读取xml

1、前台读取:

例如:<Window.Resources>

<XmlDataProvider x:key="cities" Soure="文件所在的路径" XPath="xml文件中的父级元素"/>

</Window.Resources>

2、后台读取:(主要介绍的是Linq读取)(这部分属于转载)

示例XML文件:Demo.xml

复制代码代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<note>
<conf>
<to>infozero</to>
<from>lerroy</from>
<heading>测试信息</heading>
<body>第一条测试信息</body>
<title name="我的第一条消息">from myself</title>
</conf>
<conf>
<to>infozero@163.com</to>
<from>text</from>
<heading> 时刻提醒我 </heading>
<body>这是一条测试信息!</body>
<title name="我的第二条消息">from others</title>
</conf>
</note>

在程序中引用以下命名空间

复制代码代码如下:


using System;
using System.Linq;
using System.Xml.Linq;
读取代码如下:

复制代码代码如下:

class Program { static void Main(string[] args) { XDocument doc = XDocument.Load("demo.xml"); var text = from t in doc.Descendants("conf") //定位到节点 .Where(w => w.Element("to").Value.Contains('@')) //若要筛选就用上这个语句 select new { to = t.Element("to").Value,froms = t.Element("from").Value,head = t.Element("heading").Value,body = t.Element("body").Value,title = t.Element("title").Attribute("name").Value //注意此处用到 attribute }; foreach (var a in text) { Console.WriteLine(a.to); Console.WriteLine(a.froms); Console.WriteLine(a.head); Console.WriteLine(a.body); Console.WriteLine(a.title); } Console.ReadKey(); } }

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念