尝试在使用XMLSerialization时为父节点创建和xml属性

时间:2015-02-12 23:05:52

标签: vb.net xml-serialization

我正在使用.Net中的XMLSerialization类将对象序列化为XML。在尝试为XML设置特定布局时,我正在努力弄清楚如何在元素集合中向父节点添加属性(特别是下面的ProgrammingLanguages元素):

 <Devloper>
      <FirstName IsNew="true">John</FirstName>
      <LastName IsNew="true">Doe</LastName>
      <ProgrammingLanguages>
        <LanguageType isNew="true">VB</LanguageType>
        <LanguageType isNew="false">C#</LanguageType>
      </ProgrammingLanguages>
    </Devloper>

如果没有对该数据的层次结构(如FirstName和LastName元素),我可以向元素添加属性(IsNew),但是如何在ProgrammingLanguages元素中添加属性,而不是在LanguageType元素中添加属性正在使用的参数是一个列表。

以上是我使用下面的代码获得的XML输出,但我希望结果如下。:

<Devloper>
  <FirstName IsNew="true">John</FirstName>
  <LastName IsNew="true">Doe</LastName>
  **<ProgrammingLanguages isNew="true">**
    <LanguageType>VB</LanguageType>
    <LanguageType>C#</LanguageType>
  </ProgrammingLanguages>
</Devloper>

我的代码:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim dev As New Devloper
        dev.FirstName.text = "John"
        dev.FirstName.IsNew = True

        dev.LastName.text = "Doe"
        dev.LastName.IsNew = True

        Dim l1 As New LanguageType
        l1.text = "VB"
        l1.isnew = True

        Dim l2 As New LanguageType
        l2.text = "C#"
        l2.isnew = False
        dev.ProgrammingLanguages.AddRange({l1, l2})

        dev.toXML()
    End Sub
End Class

<Serializable> Public Class Devloper
    Public Sub toXML()
        Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(Devloper))
        Dim myWriter As StreamWriter = New StreamWriter("d:\myFileName.xml")
        mySerializer.Serialize(myWriter, Me)
        myWriter.Close()
    End Sub

    Public FirstName As New helperClass
    Public LastName As New helperClass
    Public ProgrammingLanguages As New List(Of LanguageType)
End Class

Public Class helperClass
    <XmlText> Public text As String
    <XmlAttribute> Public IsNew As Boolean
End Class

Public Class LanguageType
    <XmlText> Public text As String
    <XmlAttribute> Public isNew As Boolean
End Class

任何想法?

1 个答案:

答案 0 :(得分:2)

我是在c#中做到的,我认为它会对你有所帮助 我在xml文件中得到的是:

<firstClass Name="ABC">
  <CustomerPhones Count="2">
    <phone Number="123" Address="Home" />
    <phone Number="456" Address="Work" />
  </CustomerPhones>
</firstClass>

我创建了这些类:

public class firstClass
    {
        [XmlAttribute]
        public string Name { get; set; }

        public Phones CustomerPhones { get; set; }
    }
public class Phones
    {
        [XmlAttribute]
        public string Count { get; set; }
        [XmlElement("phone")]
        public List<Phone> phones { get; set; }
    }
public class Phone
    {
        [XmlAttribute]
        public string Number { get; set; }
        [XmlAttribute]
        public string Address { get; set; }
    }