使用VB.net或C#将具有不同ElementName的xml序列化为同一对象

时间:2013-11-28 16:35:44

标签: xml vb.net serialization xml-serialization xmlserializer

我可以使用不同的语言接收xml跟踪,如下例所示:

<Persona>        
    <Nombre>Josep</Nombre>        
    <Edad>26</Edad>        
</Persona>

<Person>  
    <Name>Josep</Name>  
    <Age>26</Age>  
</Person>

我需要使用VB.net或C#序列化到同一个对象。

我声明了这样的对象:

Public Class Person     
    <XmlElement(ElementName:="Nombre">  
    Public n_nombre As String  
    <XmlElement(ElementName:="Edad")>  
    Public n_edad As String  
End Class

我如何宣布承认呢?有可能吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

使用实现相同界面的模型。特定模型可以指定与语言对应的xml元素名称:

<XmlRoot("Persona")> _
Public Class Person_Es
    Implements IXMLPerson
    <XmlElement("Edad")> _
    Public Property Age As Long Implements IXMLPerson.Age
    <XmlElement("Nombre")> _
    Public Property Name As String Implements IXMLPerson.Name
    Public Sub New()
    End Sub
End Class

<XmlRoot("Person")> _
Public Class Person_En
    Implements IXMLPerson
    <XmlElement("Age")> _
    Public Property Age As Long Implements IXMLPerson.Age
    <XmlElement("Name")> _
    Public Property Name As String Implements IXMLPerson.Name
    Public Sub New()
    End Sub
End Class

Public Interface IXMLPerson
    Property Name As String
    Property Age As Long
End Interface

要将xml加载到内存中,只有正确的语言会序列化,所以我使用了嵌套的Try。如果您有多种语言,那么您可能希望更好地构建它以减少和重用代码。这适用于英语和西班牙语:

Dim filename As String = "<your file name here>"
Dim myPerson As IXMLPerson = Nothing
Try
    Dim serializer As New XmlSerializer(GetType(Person_Es))
    Using sr As New StreamReader(filename)
        myPerson = CType(serializer.Deserialize(sr), Person_Es)
    End Using
Catch ex1 As Exception
    Try
        Dim serializer As New XmlSerializer(GetType(Person_En))
        Using sr As New StreamReader(filename)
            myPerson = CType(serializer.Deserialize(sr), Person_En)
        End Using
    Catch ex As Exception
        MessageBox.Show("Exception: " & ex.Message)
    End Try
End Try