如何编写简短的XML结束标记而不是长尾标记?

时间:2016-01-14 09:23:39

标签: xml vb.net attributes element

请原谅我的无知,但我只是从VB开始,这是我的基本疑问。我经常搜索但我无法找到解决方案。我使用此代码:

Imports System
Imports System.Xml

Public Class Form1

  Private Sub saveXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles saveXML.Click
    Dim settings As New XmlWriterSettings()
    settings.Indent = True

    Dim XmlWrt As XmlWriter = XmlWriter.Create("MyName.xml", settings)

    With XmlWrt
        .WriteStartDocument()
        .WriteComment("XML Database.")
        .WriteStartElement("Production")
        .WriteStartElement("Order")
        .WriteStartElement("Attribute")
        .WriteAttributeString("Type", "Order ID")
        .WriteAttributeString("Value", txtFullName.Text.ToString())
        .WriteFullEndElement()
        .WriteStartElement("Email")
        .WriteString(txtEmailAddress.Text.ToString())
        .WriteEndElement()
        .WriteStartElement("Tel")
        .WriteString(txtPhoneNumber.Text.ToString())
        .WriteEndElement()
        .WriteEndElement()
        .WriteEndDocument()
        .Close()
    End With

    MessageBox.Show("XML file saved.")
  End Sub
End Class

这部分:

.WriteStartElement("Attribute")
.WriteAttributeString("Type", "Order ID")
.WriteAttributeString("Value", txtFullName.Text.ToString())
.WriteFullEndElement()

我明白了:

<Attribute Type="Order ID" Value="5"></Attribute>

您注意到我没有输入.WriteEndElement()方法以便不显示结束元素标记:

</Attribute>

我怎么写#34; /&#34;得到这个:

<Attribute Type="OrderId" Value="5"/>

1 个答案:

答案 0 :(得分:3)

您必须使用WriteEndElement()代替WriteFullEndElement()来制作

<Attribute Type="Order ID" Value="5" /> 

而不是

<Attribute Type="Order ID" Value="5"></Attribute>.

但也许你想使用XML文字,这使它更容易:

Dim xml = <?xml version="1.0" encoding="utf-8"?>
            <Production> 
            <Order> 
                <Attribute Type="Order ID" Value=<%= txtFullName.Text %> /> 
                <Email><%= txtEmailAddress.Text%></Email> 
                <Tel><%= txtPhoneNumber.Text %></Tel> 
            </Order> 
            </Production> 

xml.Save("MyName.xml")