Sulla Programmazione

Quattro chiacchere sulla programmazione e sulle bit-tecnologie con Fabrizio Cipriani

Conversioni tra System.Xml e System.Xml.Linq

Riporto qui una utile classe per la conversione di elementi System.Xml a System.Xml.Linq e viceversa:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System.Xml;
using System.Xml.Linq;

/// <summary>
/// Provides extension methods for simple conversion between System.Xml and System.Xml.Linq classes.
/// </summary>
public static class XmlLinqConversionExtensions {

    /// <summary>  
    /// Converts an XDocument to an XmlDocument.  
    /// </summary>  
    /// <param name="xdoc">The XDocument to convert.</param>  
    /// <returns>The equivalent XmlDocument.</returns>  
    public static XmlDocument ToXmlDocument(this XDocument xdoc)  
    {    
        var xmldoc = new XmlDocument();    
        xmldoc.Load(xdoc.CreateReader());    
        return xmldoc;  
    }

    /// <summary>  
    /// Converts an XmlDocument to an XDocument.  
    /// </summary>  
    /// <param name="xmldoc">The XmlDocument to convert.</param>  
    /// <returns>The equivalent XDocument.</returns>  
    public static XDocument ToXDocument(this XmlDocument xmldoc)  
    {    
        return XDocument.Load(xmldoc.CreateNavigator().ReadSubtree());  
    }

    /// <summary>  
    /// Converts an XElement to an XmlElement.  
    /// </summary> 
    /// <param name="xelement">The XElement to convert.</param>  
    /// <returns>The equivalent XmlElement.</returns>  
    public static XmlElement ToXmlElement(this XElement xelement)  
    {    
        return new XmlDocument().ReadNode(xelement.CreateReader()) as XmlElement;  
    }

    /// <summary>  
    /// Converts an XmlElement to an XElement.  
    /// </summary>  
    /// <param name="xmlelement">The XmlElement to convert.</param>  
    /// <returns>The equivalent XElement.</returns>  
    public static XElement ToXElement(this XmlElement xmlelement)  
    {    
        return XElement.Load(xmlelement.CreateNavigator().ReadSubtree());  
    }
}

Questo è il link al post originale:

http://brianary.blogspot.com/2010/02/converting-between-xdocument-and.html

Comments