c# - 为特定 id c# 插入新的 xml 节点

标签 c# xml linq

如何添加新节点,其中 id 是文本框中的某个值? 这是我的 xml:

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

所以我的问题是,我有一个文本框,我可以在其中输入学生 ID。单击按钮后,我想在信息节点中添加一个新节点,其中包含当时的日期和时间属性。

另一件事是,我希望每次单击时节点中的 innerText 从 1 更改为 0,反之亦然。所以这将是节点中的第二个属性。

下次我点击时,它假设要添加一个新节点,它会添加这个。

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

我怎样才能用 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
}

结果:

<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# - 为特定 id c# 插入新的 xml 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21563689/

相关文章:

c# - 为什么我的 List<T> 没有被序列化?

c# - 限制 ListView 中的列大于 X(NotifyPropertyChanged 不起作用)

c# - WPF中如何实现双向数据绑定(bind)?

xml - 在 REST 服务中使用 json 和 xml

java - Java 支持多少种 DBMS,哪一种最适合存储 XML?

c# - 将 XML 反序列化为扩展集合的类

c# - 为什么我有 LINQ to SQL 时还需要存储过程

c# - 在 C# 中运行 powershell,运气不太好!

visual-studio-2010 - 用户定义的表类型不适用于 Linq

c# - 如何获取一段时间内日期范围的差距