Method completed, but has no effect

I create a class for managing XML, I created an overload of my RemoveNode method

public partial class HWXml { public string XmlFile; private XmlDocument XmlDoc = new XmlDocument(); public HWXml(string XmlFile) { this.XmlFile = XmlFile; } public XmlNode SelectSingleNode(string NodePath) { XmlDoc.Load(XmlFile); return XmlDoc.SelectSingleNode(NodePath); } public void RemoveNode(XmlNode removeChild) { XmlDoc.Load(XmlFile); removeChild.ParentNode.RemoveChild(removeChild); XmlDoc.Save(XmlFile); } public void RemoveNode(string RemoveChild) { XmlDoc.Load(XmlFile); XmlNode removeChild = XmlDoc.SelectSingleNode(RemoveChild); removeChild.ParentNode.RemoveChild(removeChild); XmlDoc.Save(XmlFile); } } 

When I try to remove a node using a string parameter, it works

 private void RemoveXML_Click(object sender, RoutedEventArgs e) { MyXmlClass myXmlClass = new MyXmlClass(XmlFile); myXmlClass.RemoveNode("root/Content"); } 

But when I try to delete the node using the XmlNode parameters, it will compile, execute, not display an error message, but will not delete any effect in the XML file.

 private void RemoveXML_Click(object sender, RoutedEventArgs e) { MyXmlClass myXmlClass = new MyXmlClass(XmlFile); XmlNode node = myXmlClass.SelectSingleNode("root/Conteudo"); myXmlClass.RemoveNode(node); } 

What is the problem?

+4
source share
1 answer

XmlNode parameter is definitely not part of the XmlDoc that you load inside this method (because you have this node before loading the document). Thus, manipulations with this node do not affect the document that the node does not belong to.

In the second case, you select the node of the document that was loaded. This node belongs to the xml tree, which was just loaded into the XmlDoc , so deleting the node affects the document.

What you need to understand is how the XmlDocument loaded (the same for XDocument ):

  • If it has some nodes (previously loaded), all nodes are deleted
  • XmlReader created
  • This reader reads node input stream on node
  • For each node found, a new instance of the corresponding class is created and added to the document (for example, if the reader has read some element, then a new XmlElement is created and added to the current element of the document)

So, you get a graph of completely new objects that are not related to the objects that were created during the previous xml download. After loading the xml, the XmlDocument instance remains the same, but it has completely new objects inside.

+5
source

Source: https://habr.com/ru/post/1502070/


All Articles