无法更改XmlDocument值?

时间:2018-01-18 11:07:57

标签: c# xml

我有一个简单的功能,只需更改和读取值。

void ParseXml(string XmlFile)
{
    string totalval = "";
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(new StringReader(XmlFile));

    string xmlPathPattern = "//name";

    XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
    foreach (XmlNode node in mynodelist)
    {
        XmlNode name = node.FirstChild;
        name.Value = "asd";//here I am trying to change value
        totalval = totalval + "Name=" + name.OuterXml + "\n";
    }

    xmldoc.Save(XmlFile);
    print(totalval);
}

这是我的 .xml 文件。

<name>John</name>

我可以成功读取该值但不会更改 .xml 文件中的值。运行程序后,它必须是这样的     <name>asd</name>。  我的错误在哪里?

2 个答案:

答案 0 :(得分:0)

如果我没错 - 你需要点燃一次性以节省流量。最简单的方法 - 用using

包裹
void ParseXml(string XmlFile)
{
    string totalval = "";
    using(XmlDocument xmldoc = new XmlDocument()) 
    {
        xmldoc.Load(new StringReader(XmlFile));

        string xmlPathPattern = "//name";
        XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
        foreach (XmlNode node in mynodelist)
        {
            XmlNode name = node.FirstChild;
            name.Value = "asd";//here I am trying to change value
            totalval = totalval + "Name=" + name.OuterXml + "\n";
        }

        xmldoc.Save(XmlFile);
        print(totalval);
    }
}

答案 1 :(得分:0)

显然,XMLFile不是文件路径,而是xml字符串。因此,您应该定义一个有效的路径来保存它。

xmldoc.Save("samplefile.xml");

或者如果要将XmlFile变量设置为修改后的xml;

XmlFile = xmldoc.OuterXml;

完整的代码看起来像;

void ParseXml(string XmlFile)
{
    string totalval = "";
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(new StringReader(XmlFile));

    string xmlPathPattern = "//name";

    XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
    foreach (XmlNode node in mynodelist)
    {
        XmlNode name = node.FirstChild;
        name.Value = "asd";//here I am trying to change value
        totalval = totalval + "Name=" + name.OuterXml + "\n";
    }
    //XmlFile = xmldoc.OuterXml;
    xmldoc.Save("samplefile.xml");
    print(totalval);
}