带有筛选器的Linq-to-xml扩展方法



我有以下XML文件:

<GSP>
    <RES>
    <R N="1">
          <FS NAME="date" VALUE="2013-08-26"/>
          <MT N="Title" V="article title"/>
          <MT N="UrlTitle" V="article url title"/>
          <MT N="Description" V="Lorem ipsum dolor sit amet, consectetur adipisicing elit, deserunt mollit anim id est laborum."/>
          <MT N="IsSpecialArticle" V="true"/>
    </R>
    <R N="2">
          <FS NAME="date" VALUE="2013-08-20"/>
          <MT N="Title" V="article title 2"/>
          <MT N="UrlTitle" V="article url title 2"/>
          <MT N="Description" V="Lorem ipsum dolor sit amet, consectetur adipisicing elit, deserunt mollit anim id est laborum. 2"/>
          <MT N="IsSpecialArticle" V="false"/>
    </R>
   <R N="3">
          <FS NAME="date" VALUE="2013-08-20"/>
          <MT N="Title" V="article title 3"/>
          <MT N="UrlTitle" V="article url title 3"/>
          <MT N="Description" V="Lorem ipsum dolor sit amet, consectetur adipisicing elit, deserunt mollit anim id est laborum. 3"/>
          <MT N="IsSpecialArticle" V="true"/>
    </R>
    </RES>
</GSP>

以下代码将xml文档加载到XElement中:

XElement xElement = XElement.Load(Server.MapPath("~/Xml/samplexml.xml"));

我的问题是,我不知道如何配置下面的句子,以获得那些在元素MT上的V属性上有"true"的项目,其中N="IsSpecialArticle"。

xElement.Element("RES").Elements("R").Select(??????).Where(???);

你知道我怎么能存档吗?

提前非常感谢。

致以最良好的问候。

jose。

首先,我将把XML加载到XDocument而不是XElement:

var doc = XDocument.Load(Server.MapPath("~/Xml/samplexml.xml"));

查询:

var specialItems = from r in doc.Root.Elements("RES").Elements("R")
                   let mt = r.Elements("MT").FirstOrDefault(x => (string)x.Attribute("N") == "IsSpecialArticle")
                   let isTrue = mt != null && (bool)mt.Attribute("V")
                   where isTrue
                   select r;
xElement
.Element("RES")
.Elements("R")
.Where
(
    x=>
    x
    .Elements("MT")
    .Where
    (
        z=>
        z.Attribute("N").Value == "IsSpecialArticle"
    )
    .Select
    (
        z=>
        z.Attribute("V").Value
    ).SingleOrDefault() == "true"
)

类似这样的东西:

var res = (from p in xElement.Element("RES").Elements("R")
           where p.Elements("MT").Any(q => 
                 (string)q.Attribute("N") == "IsSpecialArticle" && 
                 (bool)q.Attribute("V") == true)
           select p).ToArray();

我们使用Any()运算符来查看R元素的"内部",然后使用XAttribute的各种显式类型转换来将属性值转换为.NET类型。

注意,(bool)q.Attribute("V") == true"太多":-)(bool)q.Attribute("V")就足够了,但我认为在这种特殊情况下,== true使表达式更可读。

如果V是可选的,您可以

                 (bool?)q.Attribute("V") == true)

注意在这种情况下CCD_ 10是必要的。

最新更新