System.InvalidOperationException: This document already has a "DocumentElement" node

I am having problem adding a new node to xmldocument (created in memory). I selected the root node using the XmlDocument.SelectSingleNode () method, it works sometimes and at other times it will give me "System.InvalidOperationException: This document already has a" DocumentElement "node." mistake. More information, this XML document is a layered XML document.

By the way, when I try to use it with a unit test, it works fine (always), when I implement it in ASP.NET 3.5, it gets weird, sometimes works and sometimes fails. Any idea why this might help? All advice and suggestions are appreciated.

Thank.

+2


source to share


3 answers


You can select the root node XmlDocument using the "DocumentElement" property. Or I think you can use the "FirstChild" property (unchecked).



System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
XmlElement rootNode = doc.DocumentElement;

      

+3


source


This worked for me.



xmlOriginFile = New XmlDocument()
xmlTargetFile = New XmlDocument()
xmlOriginFile.Load(readFile)  //readFile is a string that hold path to xml document
xmlTargetFile.Load(writeFile) //writeFile is a string that hold path to xml document 

Dim fileNav As XPathNavigator = xmlOriginFile.CreateNavigator()
Dim fileItr As XPathNodeIterator = fileNav.Select("//data")

Dim addToDestNodes As List(Of XmlNode) = New List(Of XmlNode)

While (fileItr.MoveNext())

    Dim addNode As XmlNode = CType(fileItr.Current, IHasXmlNode).GetNode()
    addToDestNodes.Add(addNode)

End While //loop thru nodes

If addToDestNodes.Count > 0 Then

    For Each addedNode As XmlNode In addToDestNodes

        Dim addTargetNode As XmlNode = xmlTargetFile.ImportNode(addedNode, True)
        xmlTargetFile.DocumentElement.AppendChild(addTargetNode)
    Next

End If

xmlTargetFile.Save(xmlTarget) //xmlTarget is a string that hold path to xml document

      

+1


source


XML has a root element and you must add a new element to that root element.

XmlElement eleParent = docDestn.CreateElement("EleParent");
XmlElement eleChild = docDestn.CreateElement("Item");
eleParent.AppendChild(eleChild);
XMLNode rootNode= xmlDoc.SelectSingleNode("RootEle");
rootNode.AppendChild(eleParent);

      

PLP ,. refer to the link: http://navinpandit.blogspot.in/2016/12/exception-this-document-already-has.html

0


source







All Articles