在 C# 中,返回不带后代的 XElement



当然这很简单,但它目前暗指我,我想将XDocument的顶级节点作为XElement返回,但不返回它的任何后代:

寻找类似以下内容的内容,但它不起作用

XElement myElement = myXDocument.Root.Element();

只想退货

<Response xmlns="someurl" xmlnsLi="thew3url">
</Response>

 <Response xmlns="someurl" xmlnsLi="thew3url">   
    <ErrorCode></ErrorCode>            
    <Status>Success</Status>    
    <Result>
    <Manufacturer>
                <ManufacturerID>46</ManufacturerID>
                <ManufacturerName>APPLE</ManufacturerName>
    </Manufacturer>    
    </Result> 
 </Response>

有两种方法可以做到这一点:

  • 创建XElement的浅拷贝,并添加属性,或
  • 创建XElement的深层副本,并删除子元素。

第一种方法浪费较少,尤其是当元素具有大量子节点时。

这是第一种方法:

XElement res = new XElement(myElement.Name);
res.Add(myElement.Attributes().ToArray());

这是第二种方法:

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();
    }
}

最新更新