0

I have a XML file like this:

<?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>

I am new to C#. I need a simple code to insert a new [site] (entered by user) under a particular [sitegroup] (also choosen by user). if the [sitegroup] supplied by user does not exist in the XML already, the code should create a new [sitegroup] at the end of the XML and then insert the new [site] in it.

Also, could you please let me know how to delete a particular [site] or/and a whole [sitegroup] from the XML?

Thanks a lot in advance.

1
  • 1
    Can you show what you have tried? Commented Mar 11, 2012 at 7:15

3 Answers 3

1

First of all your xml is invalid. Xml needs to have a root element. Let us asume your root element is sitegroups. Then you can use XLinq api in .NET Framework

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());
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot hasan. it helped a lot :)
0

this is the easiest way is linq to xml. You probably are going to have to wrap your xml structure in a root element <sitegroups>, otherwise any parsing API might not like it. I haven't run this code, but it should be very close:

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

To delete you can select the element and then user the 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");

Comments

0

Here is a code that checks first if an element exists and subsequently adds sub-element:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.