2014-10-30 79 views
0

我懷疑這是可能的,但我很好奇。是否有可能以這樣一種方式反序列化XML:使用元素的標記名稱來填充屬性值?例如,給定這樣的xml:XML反序列化設置基於元素標記的值

<Test> 
    <List> 
     <Jake Type="Dog" /> 
     <Mittens Type="Cat" /> 
    </List> 
</Test> 

可能導致像這樣的列表:

Class Animal 
    Property Name As String 
    Property Type As String 
End Class 

Name Type 
------- ------- 
Jake Dog 
Mittens Cat 
+1

好,不與XmlSerializer類,但是,你能做到這一點使用XmlDocumentReader – Icepickle 2014-10-30 19:04:11

回答

1

所以,不使用XML序列化,但是,你可以用以下的的XmlReader(XmlTextReader的)解決問題方法:

Class Animal 
    Public Property Name As String 
    Public Property Type As String 
End Class 

Function ReadDocument(filename As String) As List(Of Animal) 
    Dim lst As New List(Of Animal) 

    Dim doc As XmlReader 

    Using fs As FileStream = New FileStream(filename, FileMode.Open, FileAccess.Read) 
     doc = New Xml.XmlTextReader(fs) 
     While doc.Read() 
      If doc.NodeType <> XmlNodeType.Element Then 
       Continue While 
      End If 
      If Not String.Equals(doc.Name, "List") Then 
       Continue While 
      End If 
      While doc.Read() 
       If doc.NodeType = XmlNodeType.EndElement And String.Equals(doc.Name, "List") Then 
        Exit While 
       End If 
       If doc.NodeType <> XmlNodeType.Element Then 
        Continue While 
       End If 
       Dim ani As New Animal 
       ani.Name = doc.Name 
       If doc.MoveToAttribute("Type") Then 
        ani.Type = doc.Value 
        lst.Add(ani) 
       End If 
      End While 
     End While 
    End Using 

    Return lst 
End Function 

Sub Main() 
    Dim animals As List(Of Animal) = ReadDocument("./Animals.xml") 
    Console.WriteLine("{0}{1}{2}", "Name", vbTab, "Type") 
    For Each ani As Animal In animals 
     Console.WriteLine("{0}{1}{2}", ani.Name, vbTab, ani.Type) 
    Next 
    Console.ReadLine() 
End Sub 
+0

如果我用這個,我想我會只需要編寫一個自定義序列化terface。 – Lance 2014-10-30 19:58:24

+0

嗯,它也適應你的需求,它只是在它的使用更復雜,如果你真的想/需要它更通用,然後自定義屬性可以幫助你更多... – Icepickle 2014-10-30 20:33:44