如何以编程方式在xml配置文件中的某些位置添加节点

时间:2013-08-16 09:44:21

标签: xml vb.net

我们在50台客户端PC上安装了我们的软件。

软件从xml配置文件中选择值。每个客户端在配置文件中都有自己的个人节点值(true / false)。

现在我们正在发布一个新版本的软件,在xml配置文件中只有几个节点。

我们如何在保留节点值(true / false)的同时向客户端现有配置文件添加新节点。

注意We have to provide script to client to do this cannot do manually!

示例XML:

  <?xml version="1.0" encoding="utf-8"?>
<ApplicationSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <dbEngine>true</dbEngine> 
  <EnableAuditLogging>true</EnableAuditLogging> 
  <Schema>
    <FileNo>05</FileNo>
  </Schema> 
  <nodeToBeAdded1>
   <xml/>
   <xml/>
  </nodeToBeAdded1>
  <nodeToBeAdded2>
   <DefaultPath="c:\"/>
  </nodeToBeAdded2>
  <ExportTo>
    <ExportTo>
      <ID>0</ID>
       <Path>C:\</Path>
    </ExportTo>
  </ExportTo>
</ApplicationSettings>

2 个答案:

答案 0 :(得分:2)

以下是您可以开始使用的基本代码。

Imports System.Xml

Public Class Form1
    Private Sub Test()
        Dim xDoc As XmlDocument
        Dim root As XmlNode
        Dim n As XmlNode

        xDoc = New XmlDocument()
        xDoc.Load("F:\tmp\a.xml")
        root = xDoc.SelectSingleNode("/ApplicationSettings")
        If xDoc.SelectSingleNode("/ApplicationSettings/NodeToBeAdded1") _
            Is Nothing Then
            n = root.InsertAfter(
                xDoc.CreateNode(XmlNodeType.Element, "NodeToBeAdded1", ""),
                xDoc.SelectSingleNode("/ApplicationSettings/Schema"))
            n.AppendChild(
                xDoc.CreateNode(XmlNodeType.Element, "XMLSubSomething", ""))
        End If
        xDoc.Save("F:\tmp\b.xml")
    End Sub
End Class

答案 1 :(得分:0)

Option Explicit
Option Strict

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

Public Shared Sub Main()

    Dim doc As New XmlDocument()
    doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" & _
                "<title>Pride And Prejudice</title>" & _
                "</book>")

    Dim root As XmlNode = doc.DocumentElement

    'Create a new node. 
    Dim elem As XmlElement = doc.CreateElement("price")
    elem.InnerText = "19.95" 

    'Add the node to the document.
    root.AppendChild(elem)

    Console.WriteLine("Display the modified XML...")
    doc.Save(Console.Out)
 End Sub 'Main 
 End Class 'Sample

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild.aspx