2014-09-02 33 views
2

特定属性选择节点我想我的LINQ语句在下面的例子只的CustomField与NAME =“必需”与使用LINQ

<root> 
    <appinfo> 
     <application app_id=1234 app_name="SomeName"> 
     <customfield name="Required" value="123" /> 
     <customfield name="Not Required" value="234" /> 
     <customfield name="Not Required" value="345" /> 
     <customfield name="Not Required" value="456" /> 
     <customfield name="Not Required" value="678" /> 
     </application> 
    </appinfo> 
    ... 
    </root> 

1234,SomeName,123只需要在采摘这种情况下

下面是我试过的陈述。评论在哪里不工作

var appAI = 
     from appinfo in doc.Root.Elements() 

     let application = appinfo.Elements().First() 
     let custom_field = application.Descendants() 

     //.Where(x => (string)x.Attribute("name") == "Required" && (string)x.Attribute("value").Value !="") 
     select new 
     { 
      app_id = (string)application.Attribute("app_id"), 
      app_name = (string)application.Attribute("app_name"), 
      app_AI = custom_field 

     }; 
+0

不应该'x.Attribute( “名”)== “必需”'是'x.Attribute( “名称”)值== “必需”'? – barrick 2014-09-02 21:19:44

+0

我试了两种。没有运气.. – mhn 2014-09-02 21:26:40

回答

0

看看这是否会工作。请注意,您可以将“元素”和其他一些扩展方法直接链接到IEnumerable<T>以使其更简单。

from app in doc.Elements("appinfo").Elements("application") 
from cf in app.Elements("customfield") 
where (string)cf.Attribute("name") == "Required" 
select new 
{ 
    app_id = (string)app.Attribute("app_id"), 
    app_name = (string)app.Attribute("app_name"), 
    app_AI = (string)cf.Attribute("value") 
}; 

Descendants是很少有用的方法,因为它可以隐藏你的文档中潜在的结构性问题。除非我在其他地方执行验证(如使用XSD),否则我不会使用它。

+0

它工作..与一个小的变化。 。对于我的新XML,它必须是doc.Root.Elements。此外,cf.Attribute(“value”)。Value!=“”条件被添加 – mhn 2014-09-02 22:47:16

1

这似乎为我工作:

var results = 
    from appInfo in d.Elements() 
    let application = appInfo.Elements().First() 
    let custom_field = application.Descendants() 
     .Where(x => x.Attribute("name").Value == "Required" && x.Attribute("value").Value != "") 
     .SingleOrDefault() 
    select new 
    { 
     app_id = application.Attribute("app_id").Value, 
     app_name = application.Attribute("app_name").Value, 
     app_AI = custom_field.Attribute("value").Value 
    }; 

我觉得你的问题主要是看d.Root.Elements,而不是仅仅d.Elements

例:https://dotnetfiddle.net/XVM1qz

+0

我错过了根标签在我的问题。道歉..我试着用d.Root.Elements()。我得到的对象引用没有设置错误 – mhn 2014-09-02 22:02:26

+0

奇怪..当我尝试你的小提琴链接..即使在添加根后,它工作正常 – mhn 2014-09-02 22:05:05

+0

我发现了错误。这是因为很少节点没有应用程序的结束标记。在这里复制了相同的https://dotnetfiddle.net/YUoL4N – mhn 2014-09-02 22:24:51