简体   繁体   中英

editing xml using C#

I have that xml document :

<?xml version="1.0" encoding="utf-8" ?>

<reminders>
  <reminder>
    <Title>Alarm1</Title>
    <Description>Desc1</Description>
    <Time>03/07/2012 10:11AM</Time>
    <snooze>1</snooze>
    <repeat>None</repeat>
  </reminder>
  <reminder>
    <Title>Alarm2</Title>
    <Description>Desc2</Description>
    <Time>03/07/2012 10:11AM</Time>
    <snooze>15</snooze>
    <repeat>Daily</repeat>
  </reminder>
</reminders>

And say i would like to create a full reminder child like :

  <reminder>
    <Title>NEW-Alarm</Title>
    <Description>New-Desc</Description>
    <Time>03/07/2012 10:11AM</Time>
    <snooze>15</snooze>
    <repeat>Daily</repeat>
  </reminder>

How can i do that in C# ?

And also i`d like to edit some child like from :

<Title>NEW-Alarm</Title>

to be

<Title>Modified-NEW-Alarm</Title>

I am fresh to XML and i really did my best , actually i am opening like 13 webpages for xml but none of them has what i really need, so i`ll truly appreciate your help.

I would take a look at using XDocument. You may want to search the web for examples of creating XML with it but this answer from the unstoppable Jon Skeet is a good place to start:

XML file creation using XDocument in C#

Hope that helps.

Also see these links:

http://www.codeproject.com/Articles/169598/Parse-XML-Documents-by-XMLDocument-and-XDocument

http://www.leghumped.com/blog/2009/06/30/c-xml-with-xdocuments/

http://forums.asp.net/t/1736899.aspx/1?Help+using+XDocument+in+LINQ+with+ASP+Net+C+

You need to look into the XDocument as a way to open your XML Document and then take a look at the documentation for XElement to see how easy it is to build nodes.

Each documentation page has great samples.

Load the doc with XDocument class

Add a element (edit PATH with your data) :

XElement newEl = new XElement(new XElement("reminder",
                                new XElement("Title", "NEW-Alarm"),
                                new XElement("Description", "New-Desc"),
                                new XElement("Time", "03/07/2012 10:11AM"),
                                new XElement("snooze", "15"),
                                new XElement("repeat", "Daily")));
                    doc.Root.Add(newEl);
                    doc.Save(PATH);

To change, we must first find the element (with LINQ) and then apply the SetValue method. http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.setvalue.aspx

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