创建XML文件

时间:2017-10-13 11:56:29

标签: xml vb.net

我想使用VB.net在Visual Studio中从头开始创建XML文件

我在网上找到了例子,但我很难理解如何在某些情况下添加属性和其他情况下的子元素。加上我的top元素还有其他元素。我的意思是我的格式更长,但它看起来像下面的例子:

    -<CompanyFile>
      -<Companybranch name="something">
         -<Customer>
            <name></name>
            <age></age>
            <address>
               <addreesLine > </addreesLine>
             <address>
            </Customer>
        </Companybranch>
       </CompanyFile>

我找到了一个基本XML格式的链接。

    Imports System.Xml

      Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim writer As New XmlTextWriter("product.xml", System.Text.Encoding.UTF8)
    writer.WriteStartDocument(True)
    writer.Formatting = Formatting.Indented
    writer.Indentation = 2
    writer.WriteStartElement("Table")
    createNode(1, "Product 1", "1000", writer)
    createNode(2, "Product 2", "2000", writer)
    createNode(3, "Product 3", "3000", writer)
    createNode(4, "Product 4", "4000", writer)
    writer.WriteEndElement()
    writer.WriteEndDocument()
    writer.Close()
End Sub
Private Sub createNode(ByVal pID As String, ByVal pName As String, ByVal pPrice As String, ByVal writer As XmlTextWriter)
    writer.WriteStartElement("Product")
    writer.WriteStartElement("Product_id")
    writer.WriteString(pID)
    writer.WriteEndElement()
    writer.WriteStartElement("Product_name")
    writer.WriteString(pName)
    writer.WriteEndElement()
    writer.WriteStartElement("Product_price")
    writer.WriteString(pPrice)
    writer.WriteEndElement()
    writer.WriteEndElement()
End Sub

结束班

如何创建我想要的内容一个节点有元素列表,那么元素列表可能有也可能没有子元素或属性。?

谢谢!

3 个答案:

答案 0 :(得分:3)

您可以使用只有vb.net语言的功能 - XML Literalsembed expressions

Dim companyBranchName As String = "My Company"
Dim customerName As String = "Some customer Ltd"
Dim customerAge As Integer = 33
Dim addressLine As String = "Line 12"

Dim document As XDocument = <?xml version="1.0" encoding="UTF-8"?>
                            <CompanyFile>
                                <Companybranch name=<%= companyBranchName %>>
                                    <Customer>
                                        <name><%= customerName %></name>
                                        <age><%= customerAge %></age>
                                        <address>
                                            <addreesLine><%= addressLine %></addreesLine>
                                        <address>
                                    </Customer>
                                </Companybranch>
                            </CompanyFile>

document.Save("path-to-the-file.xml)

另一种方法是使用序列化。 XmlSerializer Class
创建表示数据结构的类

Public Class CompanyFile
    Public Property CompanyBranch As CompanyBranch
End Class

Public Class CompanyBranch
    <XmlAttribute("name")> ' use attributes for explicitly declaring serialization logic
    Public Property Name As String
    Public Property Customer As Customer
End Class

Public Class Customer
    Public Property Name As String
    Public Property Age As Integer
    Public Property Address As Address
End Class

Public Class Address
    Public Property AddressLine As String
End Class

然后将数据序列化到文件

Dim data = New CompanyFile With
{
    .CompanyBranch = New CompanyBranch With
    {
        .Name = "something",
        .Customer = New Customer With
        {
            .Name = "customer name",
            .Age = 33,
            .Address = New Address With
            {
                .AddressLine = "Line 33"
            }
        }
    }
}

Dim serializer = New XmlSerializer(GetType(CompanyFile))
Using writer As New StreamWriter("path-to-file.xml")
    serializer.Serialize(writer, data)  
End Using

或者如其他答案中提到的LINQ to Xml

Dim xmlDeclaration As New XDeclaration("1.0", "UTF-8", "yes")
Dim document As XDocument = _
    New XDocument(xmlDeclaration,
                  new XElement("CompanyFile", 
                               new XElement("CompanyBranch",
                                            new XAttrbute("name", companyName),
                                            new XElement("Customer", "..."))));

document.Save("path-to-the-file.xml)

如果您要保存大量数据,那么您可以将原始方法与XmlWriter一起使用,它可读性较差且难以维护,但对于大量数据非常有效,{{ 1}}你不需要在内存中有完整的数据 - 你可以用较小的块来写数据。

XmlWriter

答案 1 :(得分:0)

我会使用Xml Linq,它是一个较新的网络库,具有比旧的Xml Net库更好的功能。

见下面的代码:

Imports System.Xml
Imports System.Xml.Linq
Module Module1

    Sub Main()
        Dim companyName As String = "Acme"
        Dim customerName As String = "John"
        Dim age As Integer = 2525
        Dim address As String = "123 Main St."

        Dim companyFile As XElement = New XElement("CompanyFile",
            New XElement("Companybranch", New Object() {
                         New XAttribute("name", companyName),
                         New XElement("Customer", New Object() { _
                                      New XElement("name", customerName),
                                      New XElement("age", age),
                                      New XElement("address",
                                                   New XElement("addressLine", address))
                                  })
                     })
             )

    End Sub

End Module

答案 2 :(得分:0)

使用XML序列化

使用这些课程,

<Xml.Serialization.XmlRoot>
Public Class CompanyFile
    <Xml.Serialization.XmlElement>
    Public Property Companybranch() As Companybranch
End Class

Public Class Companybranch
    <Xml.Serialization.XmlElement>
    Public Property Customer() As Customer
    <Xml.Serialization.XmlAttribute>
    Public Property name() As String
End Class

Public Class Customer
    <Xml.Serialization.XmlElement>
    Public Property name As String
    <Xml.Serialization.XmlElement>
    Public Property age As Integer
    <Xml.Serialization.XmlElement>
    Public Property address As address
End Class

Public Class address
    <Xml.Serialization.XmlElement>
    Public Property addreesLine As String
End Class

和这段代码,

Dim cf As New CompanyFile()
cf.Companybranch = New Companybranch() With {.name = "company name"}
cf.Companybranch.Customer = New Customer() With {.name = "person name", .age = 4}
cf.Companybranch.Customer.address = New address() With {.addreesLine = "123 abc st."}

Dim s As New Xml.Serialization.XmlSerializer(GetType(CompanyFile))

Using fs As New System.IO.FileStream("file.xml", System.IO.FileMode.OpenOrCreate)
    s.Serialize(fs, cf)
End Using

你可以写这个xml文件,

<?xml version="1.0"?>
<CompanyFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Companybranch name="company name">
    <Customer>
      <name>person name</name>
      <age>4</age>
      <address>
        <addreesLine>123 abc st.</addreesLine>
      </address>
    </Customer>
  </Companybranch>
</CompanyFile>

同时使用强类型对象。