简体   繁体   中英

Insert new xml node for specific id c#

How can I add new node where id is a certain value from a textbox? This is my xml:

<Students>
   <Student>
     <id>111</id>
     <Value>1</Value>
     <information>
        <data DateTime="02.04.2014 13:00:00" Value="1"/>
     </information>
   </Student>
</Students>

So my question is, I have a textbox where I enter the student id. After clicking on a button, I want to add a new node in information node, containing the attribute date and time in that moment.

Another thing is that I want the innerText in the node to be changed from 1 to 0 and vice-versa each new time I click. So that will be the second attribute in the node.

The next time I click, it suppose to add a new node, it will add this.

     <information>
        <data DateTime="02.04.2014 13:00:00" Value="1"/>
        <data DateTime="02.04.2014 14:00:00" Value="0"/>
     </information>

How can I do it with XmlLinq?

var xdoc = XDocument.Load(path_to_xml);
var student = xdoc.Root.Elements("Student")
                  .FirstOrDefault(s => (int)s.Element("id") == id);

if (student != null) // check if student was found
{
    var info = student.Element("information");
    if (info == null) // check if it has information element
    {
        info = new XElement("information");
        student.Add(info); // create and add information element
    }

    var lastValue = info.Elements("data")
                        .OrderBy(d => (DateTime)d.Attribute("DateTime"))
                        .Select(d => (int)d.Attribute("Value"))
                        .LastOrDefault(); // get latest value

    // create new data element
    var data = 
      new XElement("data", 
        new XAttribute("DateTime", DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss")),
        new XAttribute("Value", lastValue == 0 ? 1 : 0));

    info.Add(data); // add data element to information element
    xdoc.Save(path_to_xml); // save file
}

Result:

<Students>
  <Student>
    <id>111</id>
    <Value>1</Value>
    <information>
      <data DateTime="02.04.2014 13:00:00" Value="1" />
      <data DateTime="02.05.2014 00:40:18" Value="0" />
    </information>
  </Student>
</Students>

c# has a method that will let you do this easily:

XmlNode.InsertAfter Method

Link to the actual page: http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.insertafter(v=vs.110).aspx

Code examples if you don't want to click through:

using System;
using System.IO;
using System.Xml;

public class Sample {

public static void Main() {

XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
            "<title>Pride And Prejudice</title>" +
            "</book>");

XmlNode root = doc.DocumentElement;

//Create a new node.
XmlElement elem = doc.CreateElement("price");
elem.InnerText="19.95";

//Add the node to the document.
root.InsertAfter(elem, root.FirstChild);

Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out);

} }

If you need to find a specifc node to insert after, check this out

http://msdn.microsoft.com/en-us/library/h0hw012b(v=vs.110).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