使用XDocument.Load和XElement.Load查询XML
一、xml文件如下:
xml文件<?xml version="1.0" encoding="utf-8" ?> <DocumentElement> <IAG> <AliasName>allantsay</AliasName> <SortNo>IAG01</SortNo> <Active>N</Active> <ActiveForWOP>N</ActiveForWOP> </IAG> <IAG> <AliasName>朱亚光</AliasName> <SortNo>IAG02</SortNo> <Active>N</Active> <ActiveForWOP>Y</ActiveForWOP> </IAG> <IAG> <AliasName>张沈伟</AliasName> <SortNo>IAG03</SortNo> <Active>Y</Active> <ActiveForWOP>Y</ActiveForWOP> </IAG> <IAG> <AliasName>程康</AliasName> <SortNo>IAG04</SortNo> <Active>Y</Active> <ActiveForWOP>Y</ActiveForWOP> </IAG> </DocumentElement>查询代码如下:
二、使用XDocument.Load文件,查询结果:
包括3个小例子:1. result为XElements,但只有一个结果返回,element为<IAG><AliasName>程康</AliasName><Active>..........</IAG>
2. 与1效果相同,只是增加了排序,返回两个结果,Active为Y的。
3. 与2效果相同,只是将返回值赋给两个字符串。
查询1string xmlFilePath = Server.MapPath("IAGSalesList.xml");//xml文件存放的路径 XDocument doc = XDocument.Load(xmlFilePath); IEnumerable<XElement> elements = from result in doc.Root.Elements("IAG") where (string)result.Element("AliasName") == "程康" select result; foreach (XElement element in elements) { string s = element.Element("AliasName").Value; string s1 = element.Element("Active").Value; string s2 = element.Element("SortNo").Value; } IEnumerable<XElement> matches = from result in doc.Root.Elements("IAG") where (string)result.Element("Active") == "Y" orderby (string)result.Element("SortNo") descending select result; foreach (XElement element in matches) { string s = element.Element("AliasName").Value; string s1 = element.Element("Active").Value; string s2 = element.Element("SortNo").Value; } var matches1 = from result in doc.Root.Elements("IAG") where (string)result.Element("Active") == "Y" orderby (string)result.Element("SortNo") descending select new { aliasName = (string)result.Element("AliasName"), sortNo = (string)result.Element("SortNo") }; foreach (var element in matches1) { string s = element.aliasName; string s1 = element.sortNo; }
三、使用XElement.Load,查询结果如下:使用XElement.Load,就不能使用doc.Root.Elements("")了。
包括3个例子。1. 返回一个结果,内容为<SortNo>IAG04</SorNo>
2. 将result.Element("SortNo"从select中移到in中,效果相同,返回4个结果,内容为<AliasName>allantsay</AliasName>
<AliasName>..............................
3. 使用Descendants方式,结果与2一样。
查询2string xmlFilePath = Server.MapPath("IAGSalesList.xml");//xml文件存放的路径 XElement doc = XElement.Load(xmlFilePath); IEnumerable<XElement> elements = from result in doc.Elements("IAG") where (string)result.Element("AliasName") == "程康" select result.Element("SortNo"); foreach (XElement element in elements) { string s2 = element.Value; } IEnumerable<XElement> elements1 = from result in doc.Elements("IAG").Elements("AliasName") select result; foreach (XElement element in elements1) { string s2 = element.Value; } IEnumerable<XElement> elements2 = from result in doc.Descendants("AliasName") select result; foreach (XElement element in elements2) { string s2 = element.Value; }