我试图在下面的XML中添加(插入)新的<Period></Period>
元素;C# - 使用LINQ XML向XML文件添加新元素(XDocument/XElement)
<?xml version="1.0" encoding="utf-8"?>
<Scheduler>
<Module guid="64A3EB4C-7F34-47F3-8894-933CB0048D87">
<RetrieveDays>1</RetrieveDays>
<Schedule>
<Period>1</Period>
<Period>33</Period>
<Period>49</Period>
<Period>73</Period>
</Schedule>
</Module>
</Scheduler>
因此,例如,我传递值96,新的XML将看起来像;
<?xml version="1.0" encoding="utf-8"?>
<Scheduler>
<Module guid="64A3EB4C-7F34-47F3-8894-933CB0048D87">
<RetrieveDays>1</RetrieveDays>
<Schedule>
<Period>1</Period>
<Period>33</Period>
<Period>49</Period>
<Period>73</Period>
<Period>96</Period>
</Schedule>
</Module>
</Scheduler>
使用下面的代码;
// period is the new value
XDocument xmlDoc = new XDocument();
xmlDoc = XDocument.Load(String.Format(@"{0}\{1}", settingsDir, settingsFilename));
XElement periodNodes = xmlDoc.Root.Descendants("Module").Where(i => (String)i.Attribute("guid") == moduleGuId).First().Element("Schedule");
if (periodNodes.Descendants("Period").Where(x => x.Value == period.ToString()).Count() == 0)
periodNodes.Add(new XElement("Period", period.ToString()));
xmlDoc.Save(String.Format(@"{0}\{1}", settingsDir, settingsFilename));
但遗憾的是没有新的<Period></Period>
元素被创建。我检查了XML是有效的,它是。我尝试重命名元素,但没有改变。
我一直在挠我的头几个小时,找不到解决方案,我错过了什么?任何帮助,将不胜感激!
**** ****更新
那么,这是尴尬的:我重新启动电脑,VS和现在的作品...进入数字。尽管如此,谢谢大家如此快速的回应和建议。
有你通过它加强并检查'periodNodes.Add'实际上是叫? –
在问我们之前,您可以[使用调试器](http://www.codeproject.com/Articles/79508/Mastering-Debugging-in-Visual-Studio-A-Beginn)遍历代码并检查你的'if'语句中的子句实际上评估为真,如果不是,为什么不 –
检查[这个小提琴](https://dotnetfiddle.net/Wfh7iq) - 你的代码工作正常。如果您仍然遇到问题,请添加[mcve]。 –