Converting XElement into XmlNode

前端 未结 6 1492
逝去的感伤
逝去的感伤 2021-02-12 06:56

I know there is no direct method of doing it but still.. Can we convert XElement element into XmlNode. Options like InnerText and

6条回答
  •  梦谈多话
    2021-02-12 07:46

    Based on BrokenGlass's answer, if you wish to embed the XmlNode to an XmlDocument, than use:

    public static class MyExtensions
    {
        public static XmlNode ToXmlNode(this XElement element, XmlDocument xmlDoc = null)
        {
            using (XmlReader xmlReader = element.CreateReader())
            {
                if(xmlDoc==null) xmlDoc = new XmlDocument();
                return xmlDoc.ReadNode(xmlReader);
            }
        }
    }
    

    Note: if you try to insert into a document a node, that is created by a different document, than it will throw an exception: "The node to be inserted is from a different document context."

提交回复
热议问题