tags:

views:

36

answers:

2

i like to retrieve datas from xml file using linq. i verified lot of examples ,all examples shows retrieved element in the form of XElement but retrieve in the form of XMLNode. is it possible to do like that else how can i convert XElement into xmlnode ,how can i do this.i need it in XMLBound Element not in XMLDocment.

+1  A: 

You can write an extension for linq.

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

Since you have your XElement,you can convert it.(blog post)

element.GetXmlNode();

Hope this helps
Myra

Myra
A: 

The following method will convert any XNode into an XmlNode

XmlDocument doc = new XmlDocument(); //cached as a member variable for performance.
//recreating it inside ToXmlNode works fine too.

XmlNode ToXmlNode(XNode xnode) {
    using(var reader = myElem.CreateReader())
        return doc.ReadNode(reader);
}

That means it'll support entire documents, individual elements, text nodes, comments, processing instructions - most things except XAttribute.

However, this is something you should avoid. Try to stick with either the new System.Xml.Linq API, not to mix it with the XmlDocument-based API. This new API is easier to work with, and in any case, mixing API's like this is makes for harder-to-maintain code. If you must mix API's, it's probably cleaner to convert the entire document at one rather than copy individual nodes back and forth, particularly if your data-structure is mutable.

However, if you just need some quick interop, the above will work fine and reasonably efficiently.

Eamon Nerbonne