2012-04-11 91 views
0

我想 “列” 的列表追加到该XML文件:vb.net追加XML项

<?xml version="1.0" encoding="UTF-8"?> 
<Conf> 
    <name List="A"> 
    <columns>1</columns> 
    <columns>2</columns> 
    <columns>3</columns> 
    <columns>4</columns> 
    <columns>5</columns> 
    <columns>6</columns> 
    </name> 
    <name List="B"> 
    <columns>1</columns> 
    <columns>2</columns> 
    <columns>3</columns> 
    <columns>4</columns> 
    <columns>5</columns> 
    <columns>6</columns> 
    <columns>9</columns> 
    </name> 
</Conf> 

我到目前为止有:

Sub NewNodeInXMLFile(ByVal strPath As String, ByVal PriceList As String, ByVal columns As List(Of String)) 
     Dim XMLd As New XmlDocument 
     XMLd.Load(strPath) 
     Dim xmlEl As XmlElement = XMLd.CreateElement("name") 
     Dim xmlAttr As XmlAttribute = XMLd.CreateAttribute("List") 
     xmlAttr.Value = PriceList 
     xmlEl.Attributes.Append(xmlAttr) 

     For Each x In columns 
      xmlEl.InnerXml = "<columns></columns>" 
      xmlEl.Item("columns").InnerText = x 
'//what goes in here to append this item? 
     Next 

     XMLd.DocumentElement.AppendChild(xmlEl) 
     XMLd.Save(strPath) 
    End Sub 

基本上,我知道对于每一件事都不会追加该项目;它只会写入列表的最后一个值。有没有办法追加这些项目?

感谢

回答

1

试试这个:

For Each x In columns 
    Dim newColumn = XMLd.CreateElement("columns") 
    newColumn.Value = x 
    xmlEl.AppendChild(newColumn) 
Next 
xml.GetElementsByTagName("PriceFilesConf")[0].AppendChild(xmlEl); 
0

您应该使用的LINQ的XElement API。更容易使用。但是,下面的代码替换你的循环代码应工作:

For Each x In columns 
    Dim newElement as XmlElement = XMLd.CreateElement("columns") 
    newElement.InnerText = x 
    xmlEl.AppendChild(newElement) 
Next 

你也想改变:

XMLd.DocumentElement.AppendChild(xmlEl) 到:XMLd.AppendChild(xmlEl)