XmlSerializer kan ikke klare at samme tag bruges til 2 forskellige typer.
Man kan naturligvis lave en wok around.
Imports System
Imports System.IO
Imports System.Linq
Imports System.Text.RegularExpressions
Imports System.Xml
Imports System.Xml.Linq
Imports System.Xml.Serialization
Namespace XmlFun
Public Class Desg
<XmlElement(ElementName := "TEXT")> _
Public Property Text() As String
End Class
Public Class Record
<XmlElement(ElementName := "DESG")> _
Public Property Desg() As String
<XmlElement(ElementName := "NAME")> _
Public Property Name() As String
<XmlElement(ElementName := "DESG2")> _
Public Property Desg2() As Desg
End Class
Public Class Program
Public Shared Sub Main(args As String())
Dim xmlstr As String = "<Record>" & vbCr & vbLf & " <DESG>TEST</DESG>" & vbCr & vbLf & " <NAME>HANSEN</NAME>" & vbCr & vbLf & " <DESG>" & vbCr & vbLf & " <TEXT>HAMMEL</TEXT>" & vbCr & vbLf & " </DESG>" & vbCr & vbLf & " </Record>"
Console.WriteLine(xmlstr)
Dim doc As New XmlDocument()
doc.LoadXml(xmlstr)
Console.WriteLine(doc.DocumentElement.ChildNodes(0).FirstChild.Value)
Console.WriteLine(doc.DocumentElement.ChildNodes(2).ChildNodes(0).FirstChild.Value)
Dim xd As XDocument = XDocument.Parse(xmlstr)
Console.WriteLine(xd.Root.Elements("DESG").ToArray()(0).Value)
Console.WriteLine(xd.Root.Elements("DESG").ToArray()(1).Element("TEXT").Value)
Dim ser As New XmlSerializer(GetType(Record))
Dim r As Record = DirectCast(ser.Deserialize(New StringReader(Regex.Replace(xmlstr, "<DESG>(\s*<TEXT>.*</TEXT>\s*)</DESG>", "<DESG2>$1</DESG2>", RegexOptions.Singleline))), Record)
Console.WriteLine(r.Desg)
Console.WriteLine(r.Desg2.Text)
Console.ReadKey()
End Sub
End Class
End Namespace
giver:
<Record>
<DESG>TEST</DESG>
<NAME>HANSEN</NAME>
<DESG>
<TEXT>HAMMEL</TEXT>
</DESG>
</Record>
TEST
HAMMEL
TEST
HAMMEL
TEST
HAMMEL