vb.net 创建 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46729397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:20:30  来源:igfitidea点击:

Create XML Files

xmlvb.net

提问by Warda

I want to create XML files from scratch in Visual studio using VB.net

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

I found online Example but I struggled to understand how to add in some cases attributes and other cases child element . plus my top element have other elements.I mean my format is mucher longer but it looks like the below example:

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

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

I found a link that has basic XML format.

我找到了一个具有基本 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

End Class

结束班

How can I create what I want One Node has List of elements then the list of elements may or may not have children or attributes.?

我怎样才能创建我想要的一个节点有元素列表,那么元素列表可能有也可能没有孩子或属性。?

THANK YOU!

谢谢你!

回答by Fabio

You can use feature that only vb.net language have - XML Literalswith embed expressions.

您可以使用只有 vb.net 语言才有的功能 - XML 文字嵌入表达式

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)

Another approach is using serialization. XmlSerializer Class
Create classes which represent your data structures

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

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

Then serialize data to the file

然后将数据序列化到文件中

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

Or se LINQ to Xml as mentioned in other answer

或者像其他答案中提到的那样使用 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)

In case you going to save very big amount of data, then you can use your original approach with XmlWriter, it less readable and more difficult to maintain, but very efficient with big amount of data, with XmlWriteryou don't need to have whole data in memory - you can write data in smaller chunks.

如果您要保存非常大量的数据,那么您可以使用原始方法与XmlWriter,它的可读性较差且更难以维护,但对于大量数据非常有效,XmlWriter您不需要将整个数据放入内存 - 您可以以较小的块写入数据。

Dim settings As New XmlWriterSettings With
{
    settings.Indent = True
}    
Using writer As XmlWriter = XmlWriter.Create("path-to-file.xml", settings)
    writer.WriteStartElement("CompanyFile")
    ' other elements
    writer.WriteEndElement()
End Using

回答by jdweng

I would use Xml Linq which is a newer Net library with better features then the older Xml Net library.

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

See code below :

见下面的代码:

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

回答by djv

Using XML Serialization

使用 XML 序列化

With these classes,

有了这些课,

<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

and this code,

和这段代码,

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

you can write this xml file,

你可以写这个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>

all while using strongly-typed objects.

同时使用强类型对象。