删除C#中的部分XML

本文关键字:XML 删除 | 更新日期: 2023-09-27 17:49:26

我的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>    

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

删除C#中的部分XML

您可以使用System.Xml.XmlDocument类来修改C#中的XML文档。请注意,此类位于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");