Editing an XML file using selectsinglenode in Excel causes all code to be erased?



I have an excel macro that opens an infopath (.xml) file and allows the user to modify specific nodes using the SelectSingleNode method. However, sometimes (not all the time) after the user modifies the node and saves the document, the file gets corrupted somehow and all xml code is deleted. When I try to re-open the file in infopath, I get a "Cannot open file. Not a valid xml file" error. Sure enough, the file size is 0 Kb. After searching for days, I cannot find out why this is happening. Has anyone experienced an issue like this before?


My vba code:



Dim xDoc As new MSXML2.DOMDocument //global declaration

Private Sub ChangeXML(ByVal TargetLabel As String, ByVal LabelValue As String) //modifies the target node in Infopath form

Dim xNode As IXMLDOMNode
xDoc.async = False
If xDoc.Load(xPath & xFile) Then
Set xNode = xDoc.SelectSingleNode("//my:" & TargetLabel) //Node to modify is determined by which label is clicked on the userform
xNode.Attributes.removeNamedItem ("xsi:nil") //This method was added to prevent an error when modifying certain nodes.
xNode.nodeTypedValue = LabelValue
End If

End Sub


Private Sub SaveButton_Click()
xDoc.Save (xPath & xFile)
Set xDoc = Nothing
End Sub


My xml code:



. . .

//each of these nodes can be modified by clicking on a label in the userform. The node name is passed to the ChangeXML function on left-click
<my:TestDuration>0</my:TestDuration>
<my:TotalAborts>0</my:TotalAborts>
<my:UncorrectedIssues>0</my:UncorrectedIssues>
<my:TotalDownTime>0</my:TotalDownTime>
<my:TotalIssues>0</my:TotalIssues>
<my:TotalChargedHRS>0</my:TotalChargedHRS>
. . .


Again this works 90% of the time with no issues but sometimes it completely wipes out all xml code. Please help if you can.


No comments:

Post a Comment