微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何更新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属性更新它.但是,它仅在内存中应用更新.你确实需要重写整个文件 – 你不能只更新它的一小部分(至少,没有大量的工作和没有开箱即用的支持).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。