问题描述
我可以添加一个新的子“CharacterDevelopmentID”和一个增量 ID 作为“Characterdevelpments”的内文 - 没问题。这让我:
<S2SProject>
<CharacterDevelopments>
<CharacterDevelopmentID>1</CharacterDevelopmentID>
<CharacterDevelopmentID>2</CharacterDevelopmentID>
</CharacterDevelopments>
</S2SProject>
添加 CharacterDevelopmentID 后,我需要添加一个额外的子“CharacterDevelopmentName”,但仅限于刚刚创建的 CharacterDevelopmentID 所以新的 XML 应该是这样的:
<S2SProject>
<CharacterDevelopments>
<CharacterDevelopmentID>1
<CharacterDevelopmentName>another test</CharacterDevelopmentName>
</CharacterDevelopmentID>
<CharacterDevelopmentID>2
<CharacterDevelopmentName>yet another test</CharacterDevelopmentName>
</CharacterDevelopmentID>
</CharacterDevelopments>
</S2SProject>
我不知道如何以编程方式选择节点。 每当我尝试根据 ID nr 选择节点时,什么都没有发生
fullPath = TSProjectProjectLocation.Text & "\" & TSProjectProjectName.Text
xmlDoc.Load(fullPath)
Dim elemList As XmlNodeList = xmlDoc.GetElementsByTagName("CharacterDevelopmentID")
Dim i As Integer = elemList.Count + 1
newChild = CType(xmlDoc.CreateNode(Xml.XmlNodeType.Element,"CharacterDevelopment",""),XmlElement)
newChild.SetAttribute("CharacterDevelopmentID",i)
childnode = xmlDoc.CreateElement("CharacterDevelopmentID",i)
Dim elem1 As XmlElement
elem1 = xmlDoc.CreateElement("CharacterDevelopmentID")
elem1.InnerText = i
parNode = xmlDoc.SelectSingleNode("/S2SProject/CharacterDevelopments")
parNode.AppendChild(elem1)
xmlDoc.Save(fullPath) ' --- up to here it works!
elem1 = xmlDoc.CreateElement("CharacterDevelopmentName")
elem1.InnerText = NewCharacterDevelopmentName
parNode = xmlDoc.SelectSingleNode("/S2SProject/CharacterDevelopments/CharacterDevelopmentID[last()]/]") '-- this gives an error XpathException
parNode.AppendChild(elem1)
xmlDoc.Save(fullPath)
我尝试了很多方法来让程序选择正确的节点,但无济于事。 任何人都可以指出我正确的方向吗? 任何能帮助我解决这个问题的东西都将不胜感激!
解决方法
我正准备下班,但我会留下一些代码让你思考。
Dim xe As XElement
' for production use
' xe = XElement.Load("path here")
'for testing use literal
xe = <S2SProject>
<CharacterDevelopments>
</CharacterDevelopments>
</S2SProject>
'add some CharacterDevelopmentID
For x As Integer = 1 To 9
xe.<CharacterDevelopments>.FirstOrDefault.Add(<CharacterDevelopmentID><%= x %></CharacterDevelopmentID>)
Next
'select a particular CharacterDevelopmentID
Dim sel As IEnumerable(Of XElement)
sel = From el In xe.<CharacterDevelopments>.<CharacterDevelopmentID>
Where el.FirstNode.ToString = "7"
Select el Take 1
If sel.Count = 1 Then
sel(0).LastNode.AddAfterSelf(<CharacterDevelopmentName>another test</CharacterDevelopmentName>)
End If