using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace LinqToXml
{
class Program
{
//初始化XML数据
private static string xmlString =
@"<Persons>
<Person Id='1'>
<Name>张三</Name>
<Age>18</Age>
</Person>
<Person Id='2'>
<Name>李四</Name>
<Age>20</Age>
</Person>
<Person Id='3'>
<Name>王五</Name>
<Age>22</Age>
</Person>
</Persons>";
static void Main(string[] args)
{
Console.WriteLine("使用XPath来对XML文件查询,查询结果为:");
UseXPathToXMLQuery();
Console.WriteLine("使用Linq来对XML文件查询,查询结果为:");
UseLinqToXmlQuery();
Console.ReadKey();
}
/// <summary>
/// 使用XPath方式来对XML文件进行查询
/// </summary>
private static void UseXPathToXMLQuery()
{
//导入XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
//创建查询XML文件的XPath
string xPath = "/Persons/Person";
//查询Person元素
XmlNodeList queryNodes = xmlDoc.SelectNodes(xPath);
foreach (XmlNode node in queryNodes)
{
//查询名字为“李四”的元素
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.InnerXml == "李四")
{
Console.WriteLine("姓名为:{0},ID为{1}", childNode.InnerXml, node.Attributes["Id"].Value);
}
}
}
}
/// <summary>
/// 使用Linq来对XML文件进行查询
/// </summary>
private static void UseLinqToXmlQuery()
{
//导入XML
XElement xmlDoc = XElement.Parse(xmlString);
//创建查询,获取姓名为“李四”的元素
var queryResult = from element in xmlDoc.Elements("Person")
where element.Element("Name").Value == "李四"
select element;
//输出查询结果
foreach (var xele in queryResult)
{
Console.WriteLine("姓名为:{0},ID为{1}", xele.Element("Name").Value, xele.Attribute("Id").Value);
}
}
}
}
LinqToXml
最新推荐文章于 2021-01-14 10:42:43 发布