简体   繁体   中英

C# linq get all items in descendant and split the value

Some time ago i asked the question how to read from a xml document and use the value (see C# xdocument read from element and put the value into string )

Now i have the following issue, the solution given in the last thread works, but only if i do this:

<root>
    <test>
        <Copy01>@SRCDIR@\test1 ,@INSTDIR@\test2</Copy01>
    </test>
</root>

but i want something like this:

<root>
    <test>
        <Copy01>@SRCDIR@\test1 ,@INSTDIR@\test2</Copy01>
        <Copy02>@SRCDIR@\test3 ,@INSTDIR@\test4</Copy02>
    </test>
</root

but with the following code in C#:

 var copyitems = doc.Descendants(param[1])

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

Value of param[1] is "test" in this case it only picks the first copy (copy01) and not the second one.

Any idea how to fix this?

Nick

You seem to want to select the child elements of the test elements. You can use SelectMany and the Elements methods to do it like this:

var copyitems =
    doc.Descendants("test") //Select all "test" elements
    .SelectMany(x => x.Elements()) //Select all children of all "test" elements
    .Select(s => 
    {
        //...
    })
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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