如何更新XML节点? [英] How to Update a XML Node?

查看:117
本文介绍了如何更新XML节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是很容易读取XML文件,并得到确切的节点文本,但我要如何更新一个新值节点?

It is easy to read an XML file and get the exact Node Text, but how do I Update that Node with a new value?

要阅读:

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();不存在,但是这就是我想要的:)

Note the line, node.Update(); does not exist, but that's what I wanted :)

我看到了XmlTextWriter的对象,但会写入整个XML到一个新的文件,我只需要在原来的节点更新一个值,我可以另存为新文件,然后将新的文件重命名为原来的名字,但...它必须是简单的做到这一点吧?

I saw the XmlTextWriter object, but it will write the entire XML to a new file, and I just need to update one value in the original Node, I can save as a new file and then rename the new file into the original name but... it has to be simpler to do this right?

任何你们都对有关样本code做到这一点?

Any of you guys have a sample code on about to do this?

感谢您

推荐答案

您不需要一个更新的方法 - 设置InnerText属性更新它。然而,它只适用于存储器的更新。您的的需要,虽然重写整个文件 - 你不能只是更新它(至少不无的很多一小部分作品的无外-the盒支持)。

You don't need an "update" method - setting the InnerText property updates it. However, it only applies the update in memory. You do need to rewrite the whole file though - you can't just update a small part of it (at least, not without a lot of work and no out-of-the-box support).

这篇关于如何更新XML节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆