如何添加新节点,其中 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/