3

I can receive a xml trace in differents languages like these examples:

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

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

And I need to serialize into the same object using VB.net or C#.

I declared the object like this:

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

How I can declare it for admit its? Is it possible?

Thank you!

1 Answer 1

2

Use models which implement the same interface. The specific model can specify the xml element name corresponding to the language:

<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

And to load the xml into memory, only the correct language will serialize, so I used nested Try. If you have many languages, you would want to architect it a little better as to reduce and reuse code. This works for english and spanish:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.