Hi,
I have an XML file populated like this (from an inherited a project):
Code:
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Info>
<I1>iVal1=</I1>
<I2>iVal2=</I2>
<I3>iVal3</I3>
</Info>
<Data>
<d1>dVal1=</d1>
<d2>dVal2</d2>
</Data>
</Root>
I would like to add another node to have this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Condition1>
<Info>
<I1>iVal1=</I1>
<I2>iVal2=</I2>
<I3>iVal3</I3>
</Info>
<Data>
<d1>dVal1=</d1>
<d2>dVal2</d2>
</Data>
<\Condition1>
<Condition2>
<Info>
<I1>a=</I1>
<I2>b=</I2>
<I3>c</I3>
</Info>
<Data>
<d1>x=</d1>
<d2>y</d2>
</Data>
<\Condition2>
</Root>
I have tried different approaches to add the node without success.
Blocks 1 and 2 result in exception: System.InvalidOperationException: 'This document already has a 'DocumentElement' node.'
Block 3 adds the condition element, but not the end element.
Code:
Public Sub WriteConfigAttribute(condition As String, iType As String, attr As String, attrValue As String, Optional root As String = "Root")
Dim xdoc As New XmlDocument()
xdoc.Load(Me.xmlFileName)
Dim n0 = xdoc.SelectSingleNode($"/{root}")
' Block 1
Dim n1 As XmlNode = xdoc.CreateNode(XmlNodeType.Element, condition, Nothing)
n0.ParentNode.AppendChild(n1)
' Block 2
Dim e = xdoc.CreateElement(condition, Nothing)
n0.ParentNode.InsertAfter(e, n0)
n0.InsertBefore(n0, Nothing)
' Block 3
Dim newNode As XmlNode = xdoc.CreateNode(XmlNodeType.Element, condition, Nothing)
xdoc.DocumentElement.AppendChild(newNode)
xdoc.Save(Me.xmlFileName)
n0 = xdoc.SelectSingleNode($"/{root}/{condition}")
<rest of the code omitted for brevity>
xdoc.Save(Me.xmlFileName)
End Sub
Any suggestions will be greatly appreciated.