加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何更新XML节点?

发布时间:2020-12-15 19:29:52 所属栏目:百科 来源:网络整理
导读:它很容易读取 XML文件并获得精确的节点文本,但如何使用新值更新该节点? 阅读: public static String GetSettings(SettingsType type,SectionType section){ XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPAT
它很容易读取 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}",section.ToString())));
        node.InnerText = value;
        node.Update();
    }
    catch (Exception ex)
    {
        throw new Exception("Error:",ex);
    }
}

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

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

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

谢谢

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读