C# Linq 获取后代的值

标签 c# xml linq

我有一个问题。

仍在开发一个项目,但我陷入困境。

我们有这样的代码:

    var copyitems = doc.Descendants(application)   // Read all descendants    
        .SelectMany(x => x.Elements("Test"))
        .Select(s =>
        {
            var splits = s.Value.Split(new string[] { "@SRCDIR@", "@INSTDIR@" }, StringSplitOptions.RemoveEmptyEntries); // split the string to separate source and destination.
            return new { Source = splits[0].Replace(",", ""), Destination = splits[1].Replace(",", "") };
        })
        .ToList();

结合此 xml 示例:

<root>
<Test>
    <Copy>@SRCDIR@\test1 ,@INSTDIR@\test1</Copy>
</Test>
<root>

但是现在 xml 变成了这样:

<root>
<Test>
   <Copy>
        <Source>@SRCDIR@\test</Source>
        <Destination>@INSTDIR@\test1</Destination>
   </Copy>
</Test>
<root>

我现在如何做同样的事情,而不是进行分割,只需读取源和目标的信息。

您还可以拥有多个副本后代以及具有其他名称但没有源值和目标值的后代

最佳答案

查找接受元素名称作为输入的 Element 方法。

var copyitems = doc.Descendants(application)   // Read all descendants    
    .SelectMany(x => x.Elements("Test"))
    .Select(s =>
    {
        return new 
               { 
                     Source = s.Element("Source").Value.Replace("@SRCDIR@", ""),
                     Destination =s.Element("Destination").Value.Replace("@INSTDIR@", "") 
               };
    })
    .ToList();

关于C# Linq 获取后代的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37805054/

相关文章:

java - 在 Java 中读取 XML 文件

c# - 使用 Linq 排序

c# - Visual Studio 改变了 Ctrl-K-D 的工作方式

c# - 如何在字符串的字符之间插入空格

c# - 返回 foreach 中的第一个元素

java - 如何从基本 xml 开始创建一个巨大的 xml (> 2GB)

c# - 从 C# 提交 Spark 作业并获得结果

ios - 在 Swift 4 IOS 中获取 XML 数据到 String

c# - 如何为嵌套集合编写 Linq 或 Lambda 表达式

C# 通用 Linq 查询