I'm using an XElement object in.Net 3.5 Framework
to load the following xml fragment.
Example XML:
<xmlfragment>
<list id="1" value="one" />
<list id="2" value="two" />
<other stuff="here" />
<more things="as well"></more>
</xmlfragment>
How can I get the descendants of xmlfragment into a string? In other words, put everything in a string except the xmlfragment tag.
The following works, but was wondering if this was the most concise way.
string results = String.Join(" ", xmlfragment.DescendantNodes().Select(x=>x.ToString()).ToArray());
As you're using .NET 3.5, there are no particularly easier ways of simplifying this - although if you find yourself needing it frequently, you could always write your own static methods to emulate the new overloads of string.Join
. It's possible that you could use a method group conversion instead of the lambda expression in the Select
call, but if you're also using an old C# compiler, that may well cause problems too. (The exact rules around type inference and method group conversions have changed over time.)
The current code will fail when there are nested elements, however. It looks like you only want the direct child nodes:
string results = string.Join(" ", xmlFragment.Nodes().Select(x => x.ToString()).ToArray());
See more on this question at Stackoverflow