如何使用命名空间反序列化一个字符串?

时间:2014-01-27 22:34:45

标签: .net xml vb.net

XML:

<?xml version="1.0" encoding="utf-8"?><string xmlns="http://www.example.com">Message received</string>

我更喜欢使用类似的扩展方法反序列化:

    <Extension()> _
    Public Sub DeserializeFromXML(ByRef objTarget As Object, ByVal strXML As String)

        Dim objXMLSerializer As New System.Xml.Serialization.XmlSerializer(objTarget.GetType())
        Dim objStringReader As New System.IO.StringReader(strXML)
        objTarget = objXMLSerializer.Deserialize(objStringReader)

    End Sub

示例:

Dim strExample As String = String.Empty
strExample.DeserializeFromXML(strXML)

这是因为命名空间而失败(没有它就可以工作)。我无法创建一个继承自String的新类,因为它是非可继承的(为了使用属性来定义命名空间)。如何使用命名空间反序列化简单的XML字符串?

1 个答案:

答案 0 :(得分:0)

我做了类似的事情,但这是使用C#.NET完成的。

请查看这是否适合您。

    public static object DeserializeXmlWithNameSpaceToObject(Type ObjectType, string xml)
    {
        object result = null;

        // identify the namespace, without a matching namespace the xml can't be serialized
        string defaultNameSpace = string.Empty;
        XmlDocument document = new XmlDocument();
        document.Load(new StringReader(xml));
        defaultNameSpace = document.DocumentElement.NamespaceURI;

        // Set the xml reader settings
        XmlReaderSettings xrs = new XmlReaderSettings();
        xrs.CheckCharacters = false;

        // Deserialize the xml into an object
        using (StringReader sr = new StringReader(xml))
        {
            using (XmlReader xr = XmlReader.Create(sr, xrs))
            {
                System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(ObjectType, defaultNameSpace);
                result = ser.Deserialize(new StringReader(xml));
            }
        }

        // return the object
        return result;
    }

使用online tool将此C#.NET代码转换为VB.NET。 这是转换后的VB.NET代码。

Public Shared Function DeserializeXmlWithNameSpaceToObject(ObjectType As Type, xml As String) As Object
    Dim result As Object = Nothing

    ' identify the namespace, without a matching namespace the xml can't be serialized
    Dim defaultNameSpace As String = String.Empty
    Dim document As New XmlDocument()
    document.Load(New StringReader(xml))
    defaultNameSpace = document.DocumentElement.NamespaceURI

    ' Set the xml reader settings
    Dim xrs As New XmlReaderSettings()
    xrs.CheckCharacters = False

    ' Deserialize the xml into an object
    Using sr As New StringReader(xml)
        Using xr As XmlReader = XmlReader.Create(sr, xrs)
            Dim ser As New System.Xml.Serialization.XmlSerializer(ObjectType, defaultNameSpace)
            result = ser.Deserialize(New StringReader(xml))
        End Using
    End Using

    ' return the object
    Return result
End Function