1
VB.net编写XML我有一个简单的类从Array
Public Class Employee
Public _id As Integer
Public _firstName As String
Public _lastName As String
Public _location As String
Public Sub New(ByVal id As Integer, ByVal firstName As String, ByVal lastName As String, location As String)
_id = id
_firstName = firstName
_lastName = lastName
_location = location
End Sub
End Class
我已经定义了一些示例数据:
Dim Employees(2) As Employee
Employees(0) = New Employee(42, "John", "Smith", "NewYork")
Employees(1) = New Employee(64, "John2", "Smith2", "Budapest")
Employees(2) = New Employee(62, "John3", "Smith3", "NewYork")
我想将其写入到XML文件如下:
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<NewYork>
<Employee>
<ID>42</ID>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Employee>
<Employee>
<ID>62</ID>
<FirstName>John3</FirstName>
<LastName>Smith3</LastName>
</Employee>
</NewYork>
<Budapest>
<Employee>
<ID>64</ID>
<FirstName>Jonh2</FirstName>
<LastName>Smith2</LastName>
</Employee>
</Budapest>
</Employees>
对于编写XML,我有以下代码:
Sub XMLWrite()
Dim Employees(2) As Employee
Employees(0) = New Employee(42, "John", "Smith", "NewYork")
Employees(1) = New Employee(64, "John2", "Smith2", "Budapest")
Employees(2) = New Employee(62, "John3", "Smith3", "NewYork")
' Create XmlWriterSettings.
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
' Create XmlWriter.
Using writer As XmlWriter = XmlWriter.Create("C:\employees.xml", settings)
' Begin writing.
writer.WriteStartDocument()
writer.WriteStartElement("Employees") ' Root.
writer.WriteStartElement("NewYork")
Dim empl As Employee
For Each empl In Employees
If empl._location = "NewYork" Then
writer.WriteStartElement("Employee")
writer.WriteElementString("ID", empl._id.ToString)
writer.WriteElementString("FirstName", empl._firstName)
writer.WriteElementString("LastName", empl._lastName)
writer.WriteEndElement()
End If
Next
writer.WriteEndElement()
writer.WriteStartElement("Budapest")
Dim empl2 As Employee
For Each empl2 In Employees
If empl2._location = "Budapest" Then
writer.WriteStartElement("Employee")
writer.WriteElementString("ID", empl2._id.ToString)
writer.WriteElementString("FirstName", empl2._firstName)
writer.WriteElementString("LastName", empl2._lastName)
writer.WriteEndElement()
End If
Next
writer.WriteEndElement()
writer.WriteEndElement()
writer.WriteEndDocument()
End Using
End Sub
我有超过1000个用户拥有30多个位置,我不想在代码中手动定义每个位置。我想转换它,代码应该确定位置,并在正确的位置父元素下创建xml元素。谢谢。
欢迎。你期望我们做什么?请说明你的问题。显示你迄今为止所尝试的内容,并指出你卡在哪里。 –