Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# Return XElement without descendants

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>
like image 315
PeteN Avatar asked Feb 20 '23 02:02

PeteN


2 Answers

There are two ways to go about doing this:

  • Make a shallow copy of the XElement, and add attributes, or
  • Make a deep copy of the XElement, 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();
like image 161
Sergey Kalinichenko Avatar answered Feb 27 '23 09:02

Sergey Kalinichenko


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();
    }
}
like image 40
Larry Avatar answered Feb 27 '23 09:02

Larry