<p>Is there an easy way with LINQ to flatten an XML file?</p>

<p>I can see a number of ways with XSLT but wondered what the best option with LINQ would be?</p>

<p>I cant put the xml structure up exactly as stackoverflow seems to filter chevron chars. But its something like this </p>

<p>nodeA </p>

<p>--nodeA1 </p>

<p>--nodeA2 </p>

<p>NodeB </p>

<p>I want to end up with </p>

<p>nodeA </p>

<p>nodeA1</p>

<p>nodeA2 </p>

<p>NodeB</p>

OK; it depends on the output you want - with XElement you'd need to do a bit of work to remove all the descendent nodes etc. However, it is actually quite simple with XmlDocument:
```
```
string xml = @"<xml><nodeA><nodeA1/><nodeA2/></nodeA><NodeB/></xml>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlDocument clone = new XmlDocument();
XmlElement root = (XmlElement) clone.AppendChild(clone.CreateElement("xml"));
foreach(XmlElement el in doc.SelectNodes("//*")) {
    root.AppendChild(clone.ImportNode(el, false));
}
Console.WriteLine(clone.OuterXml);
```
```
Outputs:
```
```
<xml><xml /><nodeA /><nodeA1 /><nodeA2 /><NodeB /></xml>
```
```
[was]
Care to define "flatten" in this context? i.e. "before" and "after"?
XDocument has Descendants() and DescendantNodes() which might do the job...