我有那个xml文件:
<?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> </reminders>
而且我想修改从Alarm1到另一个值的内在文本,所以我写了那个实际上重复整个节点的代码.
XmlDocument xml = new XmlDocument(); xml.Load("0.xml"); XmlNodeList elements = xml.SelectNodes("//reminders"); foreach (XmlNode element in elements) { if (element.InnerText == "Alarm1") { XmlNode newvalue = xml.CreateElement("MODIFIED"); element.ReplaceChild(newvalue,element); xml.Save("0.xml"); } }
然后尝试另一个代码:
foreach (XmlElement element in xml.SelectNodes("//reminder")) { if (element.InnerText == "Alarm1") { XmlNode newvalue = xml.CreateElement("MODIFIED"); element.ReplaceChild(newvalue,element); xml.Save("0.xml"); } }
但也没有工作….
编辑1:[找出一个新的代码]
XmlDocument xml = new XmlDocument(); xml.Load("0.xml"); foreach (XmlElement element in xml.SelectNodes("//reminder")) { foreach (XmlElement element1 in element) { if (element.SelectSingleNode("//Title").InnerText == "Alarm1") { XmlNode newvalue = xml.CreateElement("MODIFIED"); element.ReplaceChild(newvalue,element1); xml.Save("0.xml"); } } }
但它使得Alarm1变成了
<MODIFIED />
XmlDocument xml = new XmlDocument(); xml.Load("0.xml"); foreach (XmlElement element in xml.SelectNodes("//reminder")) { foreach (XmlElement element1 in element) { if (element.SelectSingleNode("//Title").InnerText == "Alarm1") { MessageBox.Show(element1.InnerText); XmlNode newvalue = xml.CreateElement("Title"); newvalue.InnerText = "MODIFIED"; element.ReplaceChild(newvalue,element1); xml.Save("0.xml"); } } }
我真的很感谢你的帮助和谢谢.
解决方法
尝试这个:
xml.SelectSingleNode("//reminder/Title").InnerText = "NewValue";
您的foreach行只是循环通过名为“提醒”的元素列表,而不是它的子节点.
有关详细信息,请参阅此xpath教程: