Inserting XML node at specific position

前端 未结 3 1291
遇见更好的自我
遇见更好的自我 2020-12-11 08:36

I have an XML file and I am loading it in Xmldocument. This document has a node with some child nodes like this


 
   

        
相关标签:
3条回答
  • 2020-12-11 08:46

    Here is a solution without using LINQ to XML. It's implemented as an extension method for the XmlNode class:

    public static void InsertAt(this XmlNode node, XmlNode insertingNode, int index = 0)
    {
        if(insertingNode == null)
            return;
        if (index < 0)
            index = 0;
    
        var childNodes = node.ChildNodes;
        var childrenCount = childNodes.Count;
    
        if (index >= childrenCount)
        {
            node.AppendChild(insertingNode);
            return;
        }
    
        var followingNode = childNodes[index];
    
        node.InsertBefore(insertingNode, followingNode);
    }
    

    Now, you can insert a node at the desired position as simple as:

        parentXmlNode.InsertAt(childXmlNode, 7);
    
    0 讨论(0)
  • 2020-12-11 08:54

    http://www.c-sharpcorner.com/Forums/Thread/55428/how-to-insert-xml-child-node-programmatically.aspx Cheack it!I guess it will help u.

    0 讨论(0)
  • 2020-12-11 09:10

    you can use XLinq to modify XML document

    Following is an example of xml modification

        String xmlString = "<?xml version=\"1.0\"?>"+"<xmlhere>"+
        "<somenode>"+
        " <child> </child>"+
        " <children>1</children>"+ //1
        " <children>2</children>"+ //2
        " <children>3</children>"+ // 3, I need to insert it
        " <children>4</children>"+  //4,  I need to insert this second time
        " <children>5</children>"+
        " <children>6</children>"+ 
        " <child> </child>"+
        " </somenode>"+
        "</xmlhere>";
    
        XElement root = XElement.Parse(xmlString);
        var childrens = root.Descendants("children").ToArray();
        var third = childrens[3];
        var fourth = childrens[4];
        third.AddBeforeSelf(new XElement("children"));
        fourth.AddBeforeSelf(new XElement("children"));
    
        var updatedchildren = root.Descendants("children").ToArray();
    
    0 讨论(0)
提交回复
热议问题