How can I get elements of a certain name from an XML document as an XML String? (with XDocument)

How can I get elements of a certain name from an XML document as an XML String? (with XDocument)

I.e, say I have this:

<root>
    <orange id="orange1"></orange>
    <orange id="orange2"></orange>
    <orange id="orange3"></orange>

    <apple id="apple1"></apple>
    <apple id="apple2"></apple>
    <apple id="apple3"></apple>
</root>

How can I get only the XML for the apples? Ie the XML string for those three lines?

My current code is:

using (TextReader reader = File.OpenText(xmlFilePath))
{
    XDocument xmlDocument = XDocument.Load(reader);
    string items = xmlDocument.Descendants("apple").ToString();
}

...but in this example, items ends up as: System.Xml.Linq.XContainer+<GetDescendants>d__a rather than the XML string. I can't seem to find any method which will give me back the XML for the matched elements.

Jon Skeet
people
quotationmark

The problem is that you're calling ToString() on the result of calling Descendants(). It's not really clear what you expected that to do, but you are getting the elements correctly. For example:

using (TextReader reader = File.OpenText(xmlFilePath))
{
    // Any reason for not using XDocument.Load(xmlFilePath)?
    XDocument xmlDocument = XDocument.Load(reader);
    var items = xmlDocument.Descendants("apple");
    foreach (var item in items)
    {
        Console.WriteLine(item.Attribute("id").Value); // Or whatever
    }
}

If you want to concatenate the results of converting each XElement to string, you could use:

var items = string.Join("", xmlDocument.Descendants("apple"));

or

var items = string.Concat(xmlDocument.Descendants("apple"));

people

See more on this question at Stackoverflow