Sure this is simple, but it's alluding me at the moment, i want to return the top level node of an XDocument as an XElement, but without returning any of it's descendants:
Looking for something along the lines of below, but it doesn't work
XElement myElement = myXDocument.Root.Element();
WANT TO RETURN ONLY
<Response xmlns="someurl" xmlnsLi="thew3url">
</Response>
FROM
<Response xmlns="someurl" xmlnsLi="thew3url">
<ErrorCode></ErrorCode>
<Status>Success</Status>
<Result>
<Manufacturer>
<ManufacturerID>46</ManufacturerID>
<ManufacturerName>APPLE</ManufacturerName>
</Manufacturer>
</Result>
</Response>
There are two ways to go about doing this:
XElement
, and add attributes, orXElement
, and remove sub-elements.The first way is less wasteful, especially when the element has lots of child nodes.
Here is the first way:
XElement res = new XElement(myElement.Name);
res.Add(myElement.Attributes().ToArray());
Here is the second way:
XElement res = new XElement(myElement);
res.RemoveNodes();
class Program
{
static void Main(string[] args)
{
string xml = "<Response xmlns=\"someurl\" xmlnsLi=\"thew3url\">"
+ "<ErrorCode></ErrorCode>"
+ "<Status>Success</Status>"
+ "<Result>"
+ "<Manufacturer>"
+ "<ManufacturerID>46</ManufacturerID>"
+ "<ManufacturerName>APPLE</ManufacturerName>"
+ "</Manufacturer>"
+ "</Result>"
+ "</Response>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var root = doc.FirstChild;
for (int i = root.ChildNodes.Count - 1; i >= 0; i--)
{
root.RemoveChild(root.ChildNodes[i]);
}
Console.WriteLine(doc.InnerXml);
Console.ReadKey();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With