Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

c# - Inserting XML node at specific position

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

<xml here>
 <somenode>
   <child> </child>
   <children></children>
   <children></children>
   <children></children>  // I need to insert it
   <children></children>  // I need to insert this second time
   <children></children>
   <children></children>
   <child> </child>
 <somenode>
<xml here>

here somenode has some children where first and last children node names are same where as other nodes except the first and last node has some diffrent name ( identical to each other ). I am creating a function to insert a node at specific position, I am not sure about the criteria but may be in the mid.

  • how can I insert node in specific position. I am using XMLnode.appendChild method for insertion
  • Do I need to rearrange/sort nodes after insertion. Please suggest.
  • How can I determine what is structure and how should I find where the new node should be added according to current document structure.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...