使用此示例,我将如何使用此示例更新XML文件:
<foo>
<n1>
<s1></s1>
<s2></s2>
<s3></s3>
</n1>
<n1>
<s1></s1>
<s2></s2>
<s3></s3>
</n1>
</foo>
我可以整天阅读,但对于我的生活,我似乎无法将其写回那种格式。
答案 0 :(得分: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"
答案 1 :(得分: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>
LINQ-to-XML在VB.NET中非常简单,因为它将它视为XML文字,它在幕后进行LINQ-to-XML调用。您可以使用它的write方法直接将上面的'contacts'变量写入文件。
答案 2 :(得分:0)
答案 3 :(得分:0)
您还可以查看XML序列化,您可以使用以下内容:
public class foo
{
void bar()
{
System.IO.FileInfo fi = new System.IO.FileInfo("C:\foo.xml")
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer( typeof( n1 ) );
xs.Serialize(fi.OpenWrite(),new n1());
}
}
public class n1
{
[System.Xml.Serialization.XmlElement()] public string s1 { get; set; }
[System.Xml.Serialization.XmlElement()] public string s2 { get; set; }
[System.Xml.Serialization.XmlElement()] public string s3 { get; set; }
}
答案 4 :(得分:0)
这可能会给你一些合作......
Sub Main()
Dim oXML As Xml.XmlDocument
Dim oNodes As Xml.XmlNode
Dim oNode As Xml.XmlNode
Dim sFilename As String = "D:\Junk\foo.xml"
oXML = New Xml.XmlDocument
oXML.Load(sFilename)
oNodes = oXML.DocumentElement
oNode = oNodes.ChildNodes(0)
oNode.Item("s1").InnerText = "Pink Floyd"
oNode.Item("s2").InnerText = "Dark Side of the Moon"
oNode.Item("s3").InnerText = "1973"
oNode = oNodes.ChildNodes(1)
oNode.Item("s1").InnerText = "Deep Purple"
oNode.Item("s2").InnerText = "Stormbringer"
oNode.Item("s3").InnerText = "1974"
oXML.Save(sFilename)
End Sub