这是我的xml doc:
<FolderSettings>
<quantity>0</quantity>
<FolderList>
<Folder>
<FolderName>E:\05.09.2016</FolderName>
<Checked>true</Checked>
</Folder>
<Folder>
<FolderName>E:\100CANON</FolderName>
<Checked>true</Checked>
</Folder>
<Folder>
<FolderName>G:\Sony</FolderName>
<Checked>true</Checked>
</Folder>
</FolderList>
我想将带有2个音符的Folder节点添加到FolderList节点。
<Folder>
<FolderName>E:\Nikon</FolderName>
<Checked>true</Checked>
</Folder>
每次我选择/添加一个文件夹,哪一个作为节点添加到FolderList?
我该怎么做?我尝试了几乎失败的东西。
这是我在FolderList节点中添加注释的代码
Dim xmlFile = XDocument.Load(PXmlFileName)
Dim element = <Folder>
<FolderName><%= _folderPath$ %></FolderName>
<Checked><%= "true" %></Checked>
</Folder>
Dim parent = xmlFile...<FolderList>.FirstOrDefault()
parent.Add(element)
xmlFile.Save(PXmlFileName)
由于
Public Function UpdateFolderListsIntoXML(_folderPath$) As Boolean
Dim _xdoc As New XDocument()
Try
'Loading:
_xdoc = XDocument.Load(PXmlFileName)
Dim _lamIsElementExists = Function(_elementName$)
Dim _folderlistElement As XElement
Try
_folderlistElement = _xdoc.Root.Element(_elementName$)
If Not IsNothing(_folderlistElement) Then
Return True
Else
Return False
End If
Catch ex As Exception
Return False
Finally
_folderlistElement = Nothing
End Try
End Function
If _lamIsElementExists("FolderList") = False Then
'create FolderList element
_xdoc.Root.Element("FolderSettings").Add(<FolderList>
</FolderList>)
_xdoc.Save(PXmlFileName)
'After Create "FolderList" Element loading xml file again
_xdoc = XDocument.Load(PXmlFileName)
End If
'Add New Path into FolderList Element
Dim element = <Folder>
<FolderName><%= _folderPath$ %></FolderName>
<Checked><%= "true" %></Checked>
</Folder>
Dim parent = _xdoc...<FolderList>.FirstOrDefault()
parent.Add(element)
_xdoc.Save(PXmlFileName)
Return True
Catch ex As Exception
PeX = ex
Return False
Finally
_xdoc = Nothing
End Try
End Function
这对我来说很好......我感谢任何建议,谢谢
答案 0 :(得分:1)
我建议你使用Append而不是Add ..就像我在网上找到的这个例子一样:
' create new instance of XmlDocument
Dim doc As New XmlDocument()
' load from file
doc.Load(filename)
' create node and add value
Dim node As XmlNode = doc.CreateNode(XmlNodeType.Element, "FolderList", Nothing)
'node.InnerText = "this is new node";
' create title node
Dim nodeTitle As XmlNode = doc.CreateElement("FolderName")
'add value for it
nodeTitle.InnerText = "G:\Sony"
' create Url node
Dim nodeUrl As XmlNode = doc.CreateElement("Checked")
nodeUrl.InnerText = "True"
' add to parent node
node.AppendChild(nodeTitle)
node.AppendChild(nodeUrl)
' add to elements collection
doc.DocumentElement.AppendChild(node)
' save back
doc.Save(filename)