这是我的Xml

<root>
<categories>
    <recipe id="RecipeID2">
        <name>something 1</name>
    </recipe>
    <recipe id="RecipeID2">
        <name>something 2</name>
    </recipe>
    <recipe id="RecipeID3">
        <name>something 3</name>
    </recipe>
</categories>
</root>


我正在解析客户端要在其之前或之后插入新配方的所有配方

XmlDocument xmlDocument = new XmlDocument();

xmlDocument.Load("thexmlfiles.xml");

XmlNodeList nodes = xmlDocument.SelectNodes("/root/categories//Recipe");

foreach (XmlNode node in nodes)
{
    if (node.Attributes["id"].InnerText == comboBoxInsertRecipe.Text)
    {
        node.InsertAfter(xfrag, node.ChildNodes[0]);
    }
}


预期产量:

<root>
<categories>
    <recipe id="RecipeID2">
        <name>something 1</name>
    </recipe>
    <recipe id="RecipeID2">
        <name>something 2</name>
    </recipe>
    <recipe id="NewRecipe4">
        <name>new Recipe 4</name>
    </recipe>
    <recipe id="RecipeID3">
        <name>something 3</name>
    </recipe>
</categories>
</root>


但是当我插入新食谱时,它确实像这样

<root>
<categories>
    <recipe id="RecipeID2">
        <name>something 1</name>
    </recipe>
    <recipe id="RecipeID2">
        <name>something 2</name>
    </recipe>
    <recipe id="RecipeID3">
        <name>something 3</name>
        <recipe id="NewRecipe4">
            <name>new Recipe 4</name>
        </recipe>
    </recipe>
</categories>
</root>


新配方在另一个配方内,但不在类别内

最佳答案

首先,我建议使用LINQ-to-Xml。此答案中的L2Xml示例。

XDocument xmlDocument = XDocument.Load("thexmlfiles.xml");
var root = xmlDocument.Root;
var recipes = root.Element("categories").Elements("recipe");


其次,获取要在其之前/之后插入的节点的句柄/引用。

var currentRecipe = recipes.Where(r => r.Attribute("id") == "RecipeID3")
   .FirstOrDefault();


...然后根据需要添加(使用XElement.AddAfterSelfXElement.AddBeforeSelf):

void AddNewRecipe(XElement NewRecipe, bool IsAfter, XElement CurrentRecipe) {
   if(IsAfter) {
      CurrentRecipe.AddAfterSelf(NewRecipe);
   } else {
      CurrentRecipe.AddBeforeSelf(NewRecipe);
   }
}

07-28 00:59