添加/删除XML元素的简单C#代码

本文关键字:简单 代码 元素 删除 XML 添加 | 更新日期: 2023-09-27 18:27:27

我有一个XML文件,如下所示:

<?xml version='1.0' encoding='utf-8'?>
<sitegroup name = 'healthcare'>
        <site name='A' url='a.aspx'/>
        <site name='B' url='b.aspx'/>
</sitegroup>
<sitegroup name = 'diet'>
        <site name='C' url='c.aspx'/>
    <site name='D' url='d.aspx'/>
</sitegroup>

我是C#的新手。我需要一个简单的代码来在一个特定的[站点组](也由用户选择)下插入一个新的[站点](由用户输入)。如果用户提供的[sitegroup]在XML中还不存在,代码应该在XML的末尾创建一个新的[sitegroup],然后在其中插入新的[ssite]。

另外,你能告诉我如何从XML中删除特定的[站点]或/和整个[站点组]吗?

提前非常感谢。

添加/删除XML元素的简单C#代码

首先,您的xml是无效的。Xml需要有一个根元素。让我们假设你的根元素是网站组。然后您可以在.NET Framework 中使用XLinq api

class Program
{
    static void Main(string[] args)
    {
        string xml = @"<?xml version='1.0' encoding='utf-8'?>
<sitegroups>
<sitegroup name = 'healthcare'>
        <site name='A' url='a.aspx'/>
        <site name='B' url='b.aspx'/>
</sitegroup>
<sitegroup name = 'diet'>
        <site name='C' url='c.aspx'/>
    <site name='D' url='d.aspx'/>
</sitegroup>
</sitegroups>";
        var doc  = XDocument.Parse(xml);
        XElement siteGroup = doc.Element("sitegroups").Elements().First(e => e.Attribute("name").Value == "healthcare");
        var newSite = new XElement("site", new XAttribute("name", "C"),
                                           new XAttribute("url", "http://www.google.com"));
        siteGroup.Add(newSite);
        Console.WriteLine(doc.ToString());
    }
}

这是linq到xml的最简单方法。您可能需要将xml结构包装在根元素<sitegroups>中,否则任何解析API都可能不喜欢它

    var sitegroupNameSelectedByUser = "execise";
    var siteName = "E";
    var siteUrl = "e.aspx";
    XDocument yourFile = XDocument.Load(@"yourFilename.xml");
    XElement existingSitegroup = xmldoc.XPathSelectElement("sitegroups/sitegroup[@name = sitegroupNameSelectedByUser]");
        if (existingSitegroup == null)
        {
            XElement sitegroup = new XElement("sitegroup",
                            new XAttribute("name", sitegroupNameSelectedByUser),
                            new XElement("site", 
                                new XAttribute("name", siteName),
                                new XAttribute("url", siteUrl));
            yourFile.Add(sitegroup);
        }
    yourFile.Save("new-filename.xml");

要删除,可以选择元素,然后使用Remove();。

XDocument yourFile = XDocument.Load(@"yourFilename.xml");
XElement existingSitegroup = xmldoc.XPathSelectElement("sitegroups/sitegroup[@name = sitegroupNameSelectedByUser]");
if(existingSitegroup != null)
{
    existingSitegroup.Remove();
}
yourfile.Save("new-file.xml");

这里有一个代码,它首先检查元素是否存在,然后添加子元素:

    static XElement FindElementByNameAndAttr(XElement xml, XElement elem)
    {
        var q = (from x in xml.Elements()
                where x.Name == elem.Name
                      && elem.Attributes().All(a => 
                          x.Attributes().Any(b => 
                            (a.Name == b.Name) && (a.Value == b.Value)))
                select x)
                .FirstOrDefault();
        return q;
    }
    static void Main(string[] args)
    {
        string xml1 =
            @"<?xml version='1.0' encoding='utf-8'?>
            <root>
            <sitegroup name = 'healthcare'>
                    <site name='A' url='a.aspx'/>
                    <site name='B' url='b.aspx'/>
            </sitegroup>
            <sitegroup name = 'diet'>
                    <site name='C' url='c.aspx'/>
                <site name='D' url='d.aspx'/>
            </sitegroup>
            </root>
            ";
        string groupname = "jogging"; // "diet";
        string sitename = "K";
        string siteurl = "k.aspx";
        var root = XElement.Parse(xml1);
        XElement elem = new XElement("sitegroup", new XAttribute("name", groupname));
        XElement foundgroup;
        if((foundgroup = FindElementByNameAndAttr(root, elem)) == null)
        {
            root.Add(elem);
            foundgroup = elem;
        }
        var newsite = new XElement("site", new XAttribute("name", sitename));
        XElement foundsite;
        if ((foundsite = FindElementByNameAndAttr(foundgroup, newsite)) != null)
        {
            var attr = foundsite.Attribute("url");
            if (attr != null && attr.Value != siteurl)
            {
                // error handling here
                throw new Exception("TODO");
            }
        }
        else
        {
            foundgroup.Add(newsite);
            foundsite = newsite;
        }

        foundsite.SetAttributeValue("url", siteurl);
        Console.WriteLine(root.ToString());
    }