如何更新XML节点?

bal*_*dre 3 c# xml asp.net

它很容易读取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;
}
Run Code Online (Sandbox Code Playgroud)

来写 ...?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意行,node.Update(); 不存在,但这就是我想要的:)

我看到了XmlTextWriter对象,但是它会将整个XML写入一个新文件,我只需要更新原始Node中的一个值,我可以保存为新文件,然后将新文件重命名为原始名称. ..这样做要简单吗?

你们中的任何人都有关于这样做的示例代码?

谢谢

Jon*_*eet 8

您不需要"更新"方法 - 设置InnerText属性更新它.但是,它仅在内存中应用更新.你确实需要重写整个文件 - 你不能只更新它的一小部分(至少,没有大量的工作和没有开箱即用的支持).

  • Jon所说的是,当您加载有问题的XML文档时,它会加载到应用程序的内存中.对节点的任何更新都保留在内存中的负载中.直到您将XML写回文件,并且您的应用程序检测到文件更改,这些更改才会传播给用户. (3认同)