在 C# 中删除 XML 的一部分

Delete Part Of XML in C#

我的 Visual Web Developer 项目中有一个 XML 文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<complaints>
    <complaint>
        <user>omern</user>
        <content>asd</content>
        <ID>1</ID>
    </complaint>
    <complaint>
        <user>omeromern</user>
        <content>try2</content>
        <ID>2</ID>
    </complaint>
</complaints>    

我想删除 complaint 个具有 ID 个节点的节点。我该怎么做?

您可以使用 System.Xml.XmlDocument class 修改 C# 中的 XML 文档。请注意,此 class 位于 System.Xml.dll 程序集中,因此您需要在项目中添加对 System.Xml 的引用。

using System.Xml;
internal class XmlExample
{
    /// <summary>
    /// Takes an XML string and removes complaint nodes with an ID of 2.
    /// </summary>
    /// <param name="xml">An XML document in string form.</param>
    /// <returns>The XML document with nodes removed.</returns>
    public static string StripComplaints(string xml)
    {
        XmlDocument xdoc = new XmlDocument();
        xdoc.LoadXml(xml);
        XmlNodeList nodes = xdoc.SelectNodes("/complaints/complaint[ID = '2']");
        XmlNode complaintsNode = xdoc.SelectSingleNode("/complaints");
        foreach (XmlNode n in nodes)
        {
            complaintsNode.RemoveChild(n);
        }

        return xdoc.OuterXml;
    }
}

用法:

string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
                <complaints>
                    <complaint>
                        <user>omern</user>
                        <content>asd</content>
                        <ID>1</ID>
                    </complaint>
                    <complaint>
                        <user>omeromern</user>
                        <content>try2</content>
                        <ID>2</ID>
                    </complaint>
                </complaints>";
xml = XmlExample.StripComplaints(xml);
//using System.Xml;

public string RemoveComplaintWhereIDis(string xml, string id)
{
    XmlDocument x = new XmlDocument();
    xml.LoadXml(xml);
    foreach (XmlNode xn in x.LastChild.ChildNodes)
    {
        if (xn.LastChild.InnerText == id)
        {
            x.LastChild.RemoveChild(xn);
        }
    }
    return x.OuterXml;
}

基本用法:

string x = @"<?xml version=""1.0"" encoding=""utf-8""?>
             <complaints>
                 <complaint>
                     <user>omern</user>
                     <content>asd</content>
                     <ID>1</ID>
                 </complaint>
                 <complaint>
                     <user>omeromern</user>
                     <content>try2</content>
                     <ID>2</ID>
                 </complaint>
             </complaints>";

string without2 = RemoveComplaintWhereIDis(x, "2");