Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#Linq获得后代的价值_C#_Xml_Linq - Fatal编程技术网

C#Linq获得后代的价值

C#Linq获得后代的价值,c#,xml,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[] { "@SR

我有个问题

还在做一个项目,但我被卡住了

我们有这样的代码:

    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>

@SRCDIR@\test1、@INSTDIR@\test1
但现在xml变成了这样:

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

@SRCDIR@\test
@INSTDIR@\test1
我现在怎么能做同样的事情呢,只是不做拆分,而是读取源和目标的信息


此外,您还可以有多个副本描述符,也可以有其他名称的描述符,这些名称没有源和目标值

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

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();

实际上,linq查询对这两种Xml的工作方式应该是相同的(至少是问题中显示的)

只修复了无效的
,linq代码(我删除了
应用程序
,因为我们没有它)完全相同

如果您的Xml不同,那么请显示一个代码无法工作的Xml


请注意,
element.Value
将只包含非标记,因此对于第一个
Xml
,您正在拆分:
@SRCDIR@\test1、@INSTDIR@\test2
,在第二个示例中,您正在拆分
@SRCDIR>@\test1@INSTDIR@\test2
,但由于分隔符是一致的,它只是工作。

您只需要做一个小的更改,但仍然使用
拆分方法。只需在分隔符列表中添加逗号

var separators = new string[] { "@SRCDIR@", "@INSTDIR@", "," };
var tokens = s.Value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
var source = tokens[0];
var destination = tokens[1];

你所说的用其他名称描述的
是什么意思,这是否意味着
复制下没有
目标
元素,他稍后会替换
,所以它的工作原理是一样的。我同意这会更好,但它也适用于他的原始代码。输出更多地来自于OP被“,”拆分