【发布时间】:2017-05-26 09:55:03
【问题描述】:
我有一个简单的课程
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 元素。谢谢。
【问题讨论】:
-
欢迎。你希望我们做什么?请说明您的问题。展示您迄今为止尝试过的内容并指出您遇到的问题。