2014-10-30 37 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