【发布时间】:2013-11-14 20:22:32
【问题描述】:
这是我的 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>
新配方在另一个配方中,但不在类别中
【问题讨论】:
-
您正在将所有
<Recipe>节点选择到nodes列表中 - 当然,如果您向这样的节点添加一些内容,它将在该<recipe>节点内。您需要对配方节点的 parent 进行插入 - 类似于:node.parent.Insert(....);
标签: c# xml nodes xmldocument xmlnodelist