代码之家  ›  专栏  ›  技术社区  ›  Konstantin

如何将C类转换为xmlElement或xmlDocument

  •  12
  • Konstantin  · 技术社区  · 15 年前

    我有一个 C# 要使用XmlSerializer序列化的类。但我希望将其序列化为xmlElement或xmlDocument。这是可能的,还是必须将其序列化为字符串,然后将该字符串解析回XML文档?

    3 回复  |  直到 9 年前
        1
  •  8
  •   nitzmahone    15 年前

    您可以创建一个新的XML文档,然后调用CreateNavigator().AppendChild()。这将为您提供一个XML编写器,您可以将其传递给将转储到文档根目录中的序列化方法。

        2
  •  25
  •   Dave Andersen    13 年前

    我也有这个问题,马特戴维斯提供了一个很好的解决方案。只是发布一些代码片段,因为还有更多的细节。

    Serializing:

    public static XmlElement SerializeToXmlElement(object o)
    {
        XmlDocument doc = new XmlDocument();
    
        using(XmlWriter writer = doc.CreateNavigator().AppendChild())
        {
            new XmlSerializer(o.GetType()).Serialize(writer, o);
        }
    
        return doc.DocumentElement;
    }
    

    Deserializing:

    public static T DeserializeFromXmlElement<T>(XmlElement element)
    {
        var serializer = new XmlSerializer(typeof(T));
    
        return (T)serializer.Deserialize(new XmlNodeReader(element));
    }
    
        3
  •  0
  •   Rasim Yılmaz    9 年前
    Public Shared Function ConvertClassToXml(source As Object) As XmlDocument
        Dim doc As New XmlDocument()
        Dim xmlS As New XmlSerializer(source.GetType)
        Dim stringW As New StringWriter
        xmlS.Serialize(stringW, source)
        doc.InnerXml = stringW.ToString
        Return doc
    End Function
    Public Shared Function ConvertClassToXmlString(source As Object) As String
        Dim doc As New XmlDocument()
        Dim xmlS As New XmlSerializer(source.GetType)
        Dim stringW As New StringWriter
        xmlS.Serialize(stringW, source)
        Return stringW.ToString
    End Function
    Public Shared Function ConvertXmlStringtoClass(Of T)(source As String) As T
        Dim xmlS As New XmlSerializer(GetType(T))
        Dim stringR As New StringReader(source)
        Return CType(xmlS.Deserialize(stringR), T)
    End Function
    Public Shared Function ConvertXmlToClass(Of T)(doc As XmlDocument) As T
        Dim serializer = New XmlSerializer(GetType(T))
        Return DirectCast(serializer.Deserialize(doc.CreateNavigator.ReadSubtree), T)
    End Function