【问题标题】:Remove an XML element based on child index根据子索引删除 XML 元素
【发布时间】:2017-03-16 12:55:17
【问题描述】:

我发现了这个问题: How to remove an xml element from file? 如果您知道要删除的元素中的某些信息,这似乎可以正常工作。 但是我在 ASP.NET 中有一个 OnItemDeleting 函数,其中我只有(我认为)ListView 中项目的选定索引。

如您所见,在我的 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();

如果我尝试 A 之类的东西,我不知道如何用 XmlNodeList 中的节点替换 XmlDocument 中的节点,如果我喜欢 B,它就不起作用而且很奇怪。

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>

假设我想通过单击旁边的按钮来删除 Donald Trump 项目。 selectedIndex 将为 2。

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    在您的情况下,不需要循环 XmlNodeList。

    试试这个

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

    【讨论】:

    • 非常感谢您的回答。这很完美!
    【解决方案2】:

    指定要从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();
    

    【讨论】:

    • 尽管按照我的建议工作,@Azar Shaikh 提供的解决方案是完美的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2013-01-10
    • 1970-01-01
    • 2021-11-01
    • 2018-10-31
    • 1970-01-01
    相关资源
    最近更新 更多