[英]Remove an XML element based on child index
I found this question: How to remove an xml element from file? 我发现了这个问题: 如何从文件中删除xml元素? Which seems to work fine if you know some info within the element you want to delete.
如果您知道要删除的元素中的某些信息,那么这似乎工作正常。 But I have a OnItemDeleting function in ASP.NET where I only have (I think) the Selected Index of the item in a ListView.
但我在ASP.NET中有一个OnItemDeleting函数,我只有(我认为)ListView中项目的Selected Index。
In my C# file I have defined two alternatives (A and B) as you can see, it looks like this: 在我的C#文件中,我已经定义了两个替代方案(A和B),如您所见,它看起来像这样:
System.Diagnostics.Debug.WriteLine("IN ON ITEM DELETING.");
ListView1.SelectedIndex = e.ItemIndex;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(path);
XmlNodeList nodes = xmldoc.GetElementsByTagName("EmployeeInformation");
for (int i = 0; i < nodes.Count; i++)
{
if (i == ListView1.SelectedIndex)
{
nodes[i].RemoveChild(nodes[i]); // Alt. A
xmldoc.RemoveChild(nodes[i]); // Alt. B
break;
}
}
xmldoc.Save(path);
BindDatalist();
If I try something like A, I dont know how to replace the nodes in the XmlDocument with the nodes in the XmlNodeList, and if I do like B it just doesn't work and also its weird. 如果我尝试像A这样的东西,我不知道如何用XmlNodeList中的节点替换XmlDocument中的节点,如果我喜欢B它只是不起作用,也很奇怪。
The XML file looks like this: XML文件如下所示:
<EmployeeInformation>
<Details>
<Name>Goofy</Name>
<Emp_id>Goooof</Emp_id>
<Qualification>BBA</Qualification>
</Details>
<Details>
<Name>Donald</Name>
<Emp_id>Duck</Emp_id>
<Qualification>MTech</Qualification>
</Details>
<Details>
<Name>Donald</Name>
<Emp_id>Trump</Emp_id>
<Qualification>MCA</Qualification>
</Details>
</EmployeeInformation>
So lets say I want to remove the Donald Trump item by clicking a button next to it. 因此,我想通过单击旁边的按钮来删除Donald Trump项目。 The selectedIndex would be 2.
selectedIndex为2。
Specifying that the node to be deleted from the XlmNodeList is a parent node solved the problem: 指定要从XlmNodeList中删除的节点是父节点,解决了以下问题:
ListView1.SelectedIndex = e.ItemIndex;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(path);
XmlNodeList nodes = xmldoc.GetElementsByTagName("Details");
for (int i = 0; i < nodes.Count; i++)
{
if (i == e.ItemIndex)
{
nodes[i].ParentNode.RemoveChild(nodes[i]);
break;
}
}
xmldoc.Save(path);
BindDatalist();
In your case looping XmlNodeList not required. 在你的情况下循环XmlNodeList不是必需的。
try this 尝试这个
XmlDocument doc = new XmlDocument();
doc.Load(path);
if (ListView1.SelectedIndex < doc.DocumentElement.ChildNodes.Count)
{
doc.DocumentElement.RemoveChild(doc.DocumentElement.ChildNodes[ListView1.SelectedIndex]);
doc.Save(path);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.