在C#中更改元素值的最佳方法

Spe*_*nce 14 .net c# xml

我正在尝试查看更改XML中元素值的最佳方法.

<MyXmlType>
   <MyXmlElement>Value</MyXmlElement>
</MyXmlType>
Run Code Online (Sandbox Code Playgroud)

在C#中改变"价值"的最简单和/或最好的方法是什么?

我查看了XMLDocument,它将导致整个XML文档加载到内存中.你能用XMLReader安全地完成吗?问题是改变价值并将其发回似乎是一个有趣的难题.

干杯:D

Ben*_*ins 33

您可以使用System.Xml.Linq命名空间的东西来获得最简单的代码.这会将整个文件加载到内存中.

XDocument xdoc = XDocument.Load("file.xml");
var element = xdoc.Elements("MyXmlElement").Single();
element.Value = "foo";
xdoc.Save("file.xml");
Run Code Online (Sandbox Code Playgroud)


And*_*ley 5

编辑:没有看到关于XmlDocument的条款.XmlReader就是这么做的.您无法使用此类编辑xml文件.

你想要XmlWriter.但是,如果它仍然有用,这里是XmlDocument的代码.

private void changeXMLVal(string element, string value)
{
    try
    {
        string fileLoc = "PATH_TO_XML_FILE";
        XmlDocument doc = new XmlDocument();
        doc.Load(fileLoc);
        XmlNode node = doc.SelectSingleNode("/MyXmlType/" + element);
        if (node != null)
        {
            node.InnerText = value;
        }
        else
        {
            XmlNode root = doc.DocumentElement;
            XmlElement elem;
            elem = doc.CreateElement(element);
            elem.InnerText = value;
            root.AppendChild(elem);
        }
        doc.Save(fileLoc);
        doc = null;
    }
    catch (Exception)
    {
        /*
         * Possible Exceptions:
         *  System.ArgumentException
         *  System.ArgumentNullException
         *  System.InvalidOperationException
         *  System.IO.DirectoryNotFoundException
         *  System.IO.FileNotFoundException
         *  System.IO.IOException
         *  System.IO.PathTooLongException
         *  System.NotSupportedException
         *  System.Security.SecurityException
         *  System.UnauthorizedAccessException
         *  System.UriFormatException
         *  System.Xml.XmlException
         *  System.Xml.XPath.XPathException
        */
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这确实对应于问题的标题,并帮助了我.+1 (2认同)