删除C#中的XML部分

时间:2015-05-17 20:09:32

标签: c# xml visual-web-developer

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

我想要删除complaintID的节点。我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用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);

答案 1 :(得分:1)

//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");