Converting XElement into XmlNode

前端 未结 5 1934
死守一世寂寞
死守一世寂寞 2021-02-12 07:17

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

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-12 07:44

    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."

提交回复
热议问题