locked
replace node in XMLDocument RRS feed

  • Question

  • User-1035864976 posted

    I have a XML document in which i want to replace specific node. I know i can do it by string.replace but looking for better approach
    My xml looks like:

    <node1 ..../>
    <node2..../>
    <ABCD href="http://forums.asp.net/post/set/43/0/0" class="Tools/Jar">
    <node4.....>

    I want to replace node(without changing the position) that starts with ABCD with below node

    <XYZ format="constant" href"http://forums.asp.net/post/set/43/0/0" class="Tools/bottle" />

    Thursday, April 7, 2016 5:17 AM

Answers

  • User-2057865890 posted

    Hi nileshvk,

    Use XNode.Remove and XNode.AddAfterSelf.

    XElement xmlTree = new XElement("Root",
                        new XElement("Child1", "child1 content"),
                        new XElement("Child2", "child2 content"),
                        new XElement("Child3", "child3 content"),
                        new XElement("Child4", "child4 content"),
                        new XElement("Child5", "child5 content")
                );
    
    XElement child3 = xmlTree.Element("Child3");
    xmlTree.Element("Child3").AddAfterSelf(new XElement("Child6", "child6 content"));
    
    
    child3.Remove();
    Console.WriteLine(xmlTree);

    Best Regards,

    Chris Zhao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 11, 2016 4:44 PM

All replies

  • User-2057865890 posted

    Hi nileshvk,

    You could use XmlNode.ReplaceChild Method, which replaces the child node oldChild with newChild node.

    public virtual XmlNode ReplaceChild(
    	XmlNode newChild,
    	XmlNode oldChild
    )
    

    XmlNode.ReplaceChild Method (XmlNode, XmlNode)

    Best Regards,

    Chris Zhao

    Thursday, April 7, 2016 8:50 AM
  • User-1035864976 posted

    I have tried this already.These are not the childnodes.

    Thursday, April 7, 2016 9:23 AM
  • User-2057865890 posted

    Hi nileshvk,

    Use XNode.Remove and XNode.AddAfterSelf.

    XElement xmlTree = new XElement("Root",
                        new XElement("Child1", "child1 content"),
                        new XElement("Child2", "child2 content"),
                        new XElement("Child3", "child3 content"),
                        new XElement("Child4", "child4 content"),
                        new XElement("Child5", "child5 content")
                );
    
    XElement child3 = xmlTree.Element("Child3");
    xmlTree.Element("Child3").AddAfterSelf(new XElement("Child6", "child6 content"));
    
    
    child3.Remove();
    Console.WriteLine(xmlTree);

    Best Regards,

    Chris Zhao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 11, 2016 4:44 PM