简体   繁体   中英

Modifying an XML Document Using C# Linq

I have an application that loops through an XML then downloads the files from the urls in the file My XML format is like this:

<FileDownloads>
<Downloads ID="1">
    <FriendlyName>MyFile</FriendlyName>
    <URL>http://www.MyDownloadURL.com?p=m/MyFileName</URL>
    <FileLocation>Tools\MyFIleName.exe</FileLocation>
<Selected>true</Selected>
<Switches></Switches>
</Downloads>

I am having trouble modifying elements of the XML IE: The Url if it changes and also adding and removing entire elements using Xelement.

I am trying the code Below:

public void NewXML()
    {
        try
        {
            XDocument XDocAdd = XDocument.Load(path);
            XElement DL = new XElement("Downloads");
            DL.Add(new XElement("FriendlyName", prl.textBox_FN.Text));
            DL.Add(new XElement("URL", prl.textBoxURL.Text));
            DL.Add(new XElement("FileLocation", prl.textBoxFL.Text));
            DL.Add(new XElement("Selected", prl.checkBox_DL.Checked));
            DL.Add(new XElement("Switches", prl.textBox_Switches.Text));
            XDocAdd.Element("FileDownloads").Add(DL);
           XDocAdd.Save(@"C:\Test\Test10.xml");
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message);
            MessageBox.Show(err.InnerException.ToString());
        }


    }

I am very much a noob so any help would be great!!

Try this:

XElement DL = new XElement("Downloads",
                  new XElement("FriendlyName", prl.textBox_FN.Text),
                  new XElement("URL", prl.textBoxURL.Text),
                  new XElement("FileLocation", prl.textBoxFL.Text),
                  new XElement("Selected", prl.checkBox_DL.Checked),
                  new XElement("Switches", prl.textBox_Switches.Text));
XDocAdd.Element("FileDownloads").Add(DL);

When you are creating XML with XElement you need to add them nested according to your schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM