【问题标题】:Select an element who as a last child with property选择作为最后一个具有属性的子元素的元素
【发布时间】:2019-10-31 04:47:22
【问题描述】:
<bus>
    <port>
        <req>
            <item>
            [...]
            </item> 
        </req>
        [...]
        <req>
            <item>
            [...]
            </item> 
        </req>
    </port>
    [...]
    <port>
        <req>
            <item>
            [...]
            </item> 
        </req>
        [...]
        <req>
            <item>
            [...]
            </item> 
        </req>
    </port>
</bus>
<bus>
[...] (same as before)
</bus>

我有这个结构;所有的结构都会重复。我需要选择总线的最后一个端口元素,该元素的最后一个子元素具有属性“mode”=="read"。

它可以存在一个总线,它的最后一个端口元素和最后一个子元素的属性不同于“读取”,所以我需要选择正确的端口元素。

我尝试了很多次,最后一个是这个,但不起作用:

var modbusportSelected = Elements("bus").Elements("port")
.Where( x => x.Elements("req")
.Any(y => y.Attribute("mode").Value.Contains("read")))
.Last();

任何帮助将不胜感激;另外,我对 LINQ to XML 完全陌生,我找不到一个网页来获取“任何”的确切含义,以及是否有其他运算符,如果有,它们是什么。

【问题讨论】:

  • Any 只返回一个布尔值,条件是在 any 方法中设置的。在您的情况下,您是说是否有任何模式属性的值包含 read。
  • 谢谢!你还知道我在哪里可以找到关于 Any 和其他运营商的一些不错的文档吗?

标签: c# linq linq-to-xml


【解决方案1】:

您的 XML sn-p 需要一个顶级元素可能很重要。如果您将上面的内容包装在外部标记中,那么您的代码似乎可以工作,前提是您从任何没有 mode 属性的 port 元素中捕获空引用。例如。

using System;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApp1
{
    class Program
    {
        public static string xml = @"<topLevel><bus>
    <port isCorrectNode='no'>
        <req>
            <item>
            </item> 
        </req>
        <req mode='read'>
            <item>
            </item> 
        </req>
    </port>
    <port isCorrectNode='yes'>
        <req mode='read'>
            <item>
            </item> 
        </req>
        <req>
            <item>
            </item> 
        </req>
    </port>
</bus>
<bus>
</bus>
</topLevel>";

        static void Main(string[] args)
        {
            XElement root = XElement.Parse(xml);

            var found = root.Elements("bus").Elements("port")
                .Where(x => x.Elements("req").Any(y => y.Attribute("mode") != null && y.Attribute("mode").Value.Contains("read")))
                .Last();

            var isThisTheCorrectNode = found.Attribute("isCorrectNode").Value;
            Console.WriteLine(isThisTheCorrectNode);
        }
    }
}

会写yes

编辑:我注意到您的代码会查找最后一个 port,它有 any 个子 req,其模式为“读取”。但是您的问题要求 lastreq。在这种情况下:

var wanted = root.Elements("bus").Elements("port")
    .Where(x => x.Elements("req").Any() && // make sure there is a req element
x.Elements("req").Last().Attribute("mode") != null && // and it has the attribute  
x.Elements("req").Last().Attribute("mode").Value.Contains("read")) // and it has the right value
    .Last();

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    相关资源
    最近更新 更多