如何更新XML节点?
它很容易读取XML文件并获得确切的节点文本,但如何使用新值更新该节点?
阅读:
public static String GetSettings(SettingsType type, SectionType section) { XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH)); XmlDocument document = new XmlDocument(); document.Load(reader); XmlNode node = document.SelectSingleNode( String.Format("/MyRootName/MySubNode/{0}/{1}", Enum.Parse(typeof(SettingsType), type.ToString()), Enum.Parse(typeof(SectionType), section.ToString()))); return node.InnerText; }
来写 …?
public static void SetSettings(SettingsType type, SectionType section, String value) { try { XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH)); XmlDocument document = new XmlDocument(); document.Load(reader); XmlNode node = document.SelectSingleNode( String.Format("/MyRootName/MySubNode/{0}/{1}", Enum.Parse(typeof(SettingsType), type.ToString()), Enum.Parse(typeof(SectionType), section.ToString()))); node.InnerText = value; node.Update(); } catch (Exception ex) { throw new Exception("Error:", ex); } }
注意行,node.Update(); 不存在,但这就是我想要的:)
我看到了XmlTextWriter对象,但它会将整个XML写入一个新文件,我只需要更新原始Node中的一个值,我可以保存为新文件,然后将新文件重命名为原始名称。 ..这样做要简单吗?
你们中的任何人都有关于这样做的示例代码?
谢谢
您不需要“更新”方法 – 设置InnerText属性更新它。 但是,它仅在内存中应用更新。 你确实需要重写整个文件 – 你不能只更新它的一小部分(至少,没有大量的工作和没有开箱即用的支持)。
XmlDocument.Load
有一个重载,它将直接采用文件名,因此不需要读者。
类似地,当你完成XmlDocument.Save
将采取一个文件名,它将保存文档。
nodeValue属性可用于更改文本节点的值。
以下代码更改了第一个元素的文本节点值:示例:
xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]; x.nodeValue="Easy Cooking";
来源: http : //www.w3schools.com/DOM/dom_nodes_set.asp
您正在更新xml文档的内存中表示中的节点,AFAIK无法直接在物理文件中更新节点。 您必须将它全部转储回文件。