Converting XElement into XmlNode

ⅰ亾dé卋堺 提交于 2019-12-05 09:18:58

问题


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

so,if i want to use these options, what can be done to convert XElement into XmlNode and vice versa.


回答1:


Here is converting from string to XElement to XmlNode and back to XElement. ToString() on XElement is similar to OuterXml on XmlNode.

    XElement xE = XElement.Parse("<Outer><Inner><Data /></Inner></Outer>");

    XmlDocument xD = new XmlDocument();
    xD.LoadXml(xE.ToString());
    XmlNode xN = xD.FirstChild;

    XElement xE2 = XElement.Parse(xN.OuterXml); 



回答2:


I use the following extension methods, they seem to be quite common:

public static class MyExtensions
{
    public static XElement ToXElement(this XmlNode node)
    {
        XDocument xDoc = new XDocument();
        using (XmlWriter xmlWriter = xDoc.CreateWriter())
            node.WriteTo(xmlWriter);
        return xDoc.Root;
    }

    public static XmlNode ToXmlNode(this XElement element)
    {
        using (XmlReader xmlReader = element.CreateReader())
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlReader);
            return xmlDoc;
        }
    }
}



回答3:


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




回答4:


I think the shortest way is following:

Dim xn as XmlNode = xdoc.ReadNode(xElem.CreateReader)

That's all! Convert to C# is trivial.




回答5:


There are ways to get InnerXml from XElement - see Best way to get InnerXml of an XElement?




回答6:


XElement xelement = GetXElement();
XmlNode node = new XmlDocument().ReadNode(xelement.CreateReader()) as XmlNode;


来源:https://stackoverflow.com/questions/5389525/converting-xelement-into-xmlnode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!