什么是使用VB.net 2008编写XML的好例子

5 xml vb.net linq-to-xml visual-studio-2008

使用此示例,我将如何使用此示例更新XML文件:

<foo>
   <n1>
       <s1></s1>
       <s2></s2>
       <s3></s3>
   </n1>
   <n1>
       <s1></s1>
       <s2></s2>
       <s3></s3>
   </n1>
</foo>
Run Code Online (Sandbox Code Playgroud)

我可以整天读它,但对于我的生活,我似乎无法把它写回那种格式.

Dan*_*Tao 9

直截了当的方法:

' to create the XmlDocument... '
Dim xmlDoc As New Xml.XmlDocument

Dim fooElement As Xml.XmlElement = xmlDoc.CreateElement("foo")
xmlDoc.AppendChild(fooElement)

Dim n1Element As Xml.XmlElement = xmlDoc.CreateElement("n1")
For Each n1ChildName As String In New String() {"s1", "s2", "s3"}
    Dim childElement As Xml.XmlElement = xmlDoc.CreateElement(n1ChildName)
    n1Element.AppendChild(childElement)
Next

fooElement.AppendChild(n1Element)
fooElement.AppendChild(n1Element.CloneNode(deep:=True))

' to update the XmlDocument (simple example)... '
Dim s1Element As Xml.XmlElement = xmlDoc.SelectSingleNode("foo/n1/s1")
If Not s1Element Is Nothing Then s1Element.InnerText = "some value"
Run Code Online (Sandbox Code Playgroud)


Jor*_*mer 5

在VS2008中使用LINQ-to-XML是一种很好的方法.以下是一些关键链接:

这是一个VB.NET代码段:

Dim contacts = _
    <Contacts>
        <Contact>
            <Name>Patrick Hines</Name>
            <Phone Type="Home">206-555-0144</Phone>
            <Phone Type="Work">425-555-0145</Phone>
            <Address>
                <Street1>123 Main St</Street1>
                <City>Mercer Island</City>
                <State>WA</State>
                <Postal>68042</Postal>
            </Address>
        </Contact>
    </Contacts>
Run Code Online (Sandbox Code Playgroud)

LINQ-to-XML在VB.NET中非常简单,因为它将它视为XML文字,它在幕后进行LINQ-to-XML调用.您可以使用它的write方法直接将上面的'contacts'变量写入文件.