简体   繁体   English

Linq查询基于属性

[英]Linq query based on attribute

Ran into another challenge. 进入另一个挑战。 I looked through some of the questions that I found here, but I can't seem to piece together what I need. 我查看了我在这里找到的一些问题,但我似乎无法拼凑出我需要的东西。

OK I have a XML file: 好的我有一个XML文件:

<Output id="1">
    <path rename="Off" name="pattern-1">d:\temp</path>
  </Output>

  <Output id="2">
      <path isRename="False" name="pattern-1" >d:\temp\out2</path>
      <path isRename="True"  name="pattern-1" >d:\temp\out3</path>
      <path isRename="False" name="pattern-1">d:\temp\out4</path>
  </Output>

What I need to do is find the <Output> tag based on the id attribute . 我需要做的是根据id属性找到<Output>标签。 Then I need to loop through all of the <path> tags and get the attribute and path value. 然后我需要循环遍历所有<path>标记并获取属性和路径值。 I tried a few thing based on a previous question I had asked but I couldn't get it to work 我根据之前提出的问题尝试了一些事情,但是我无法让它发挥作用

var results = from c in rootElement.Elements("Output") 
              where (string)c.Attribute("Id") == "2" select c;

foreach (var path in rootElement.Elements("Output").Elements("path"))
{
    string p  = path.Value;
}

Your first line doesn't do anything if you don't actually use the results. 如果您实际上没有使用结果,那么您的第一行不会执行任何操作。

foreach (var outputElement in rootElement.Elements("Output")
                                         .Where(e => (string)e.Attribute("id") == "1"))
{
    foreach (var pathElement in outputElement.Elements("path"))
    {
        // ...
    }
}

If your id attribute is guaranteed to be unique (which it should), you can get rid of the first foreach and just get the individual <Output> directly: 如果你的id属性保证是唯一的(它应该是),你可以摆脱第一个foreach并直接获得单独的<Output>

var outputElement = rootElement.Elements("Output")
                               .FirstOrDefault(e => (string)e.Attribute("id") == "1"));

I would recommend using some XPath to select nodes you need: 我建议使用一些XPath来选择你需要的节点:

foreach (XElement path in root.XPathSelectElements("/Output/path[../@id=1]"))
{
    string value = path.Value;
}

Indeed, sometimes XPath lets you write more readable and maintanable code. 实际上,有时XPath允许您编写更易读且可维护的代码。 You just use some expression that replaces several linq-to-xml statements. 您只需使用一些表达式替换几个linq-to-xml语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM