C# 读取保存xml文件

直接读取xml文件中的内容

         XmlDocument xmlDoc = new XmlDocument();
           xmlDoc.LoadXml(result);
           XmlNode root = xmlDoc.SelectSingleNode("//response");
           if (root != null)
            {
                string error = (root.SelectSingleNode("error")).InnerText;
            }

代码来源:https://www.cnblogs.com/kongxiaoshuang/p/6512328.html

这种方法存在一个缺点就是当xml文件中存在<!DOCTYPE>,eg:<!DOCTYPE nvidia_smi_log SYSTEM "nvsmi_device_v10.dtd"> 而你有缺少了dtd文件会导致读取xml文件报错

<!DOCTYPE>详细:http://www.w3school.com.cn/tags/tag_doctype.asp

因此需要取消对该标签的读取,这是读取nvidia-smi -p -x输出出来的显卡的显存信息

 private static void Getxml(ref string total, ref string free)
        {
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                XmlReaderSettings setting = new XmlReaderSettings();
                setting.DtdProcessing = DtdProcessing.Ignore; //忽视dtd
                XmlReader reader = XmlReader.Create(savepath, setting);
                xmldoc.Load(reader);
                XmlNodeList topM = xmldoc.SelectNodes("//fb_memory_usage");
                foreach (XmlElement element in topM)
                {
                    total = element.GetElementsByTagName("total")[0].InnerText.Replace(" MiB","");
                    free = element.GetElementsByTagName("free")[0].InnerText.Replace(" MiB", "");
                }
                reader.Close();

            }
            catch (Exception)
            {
                total = "0.0";
                free = "0.0";
            }
            finally
            {
                if (File.Exists(savepath))
                {
                    File.Delete(savepath);
                }
            }
        }

保存xml

   FileStream writeStream = new FileStream("E:\\aaaa.txt", FileMode.Create);
            XmlSerializer serializer = new XmlSerializer(data.GetType()); //xml对象
            serializer.Serialize(writeStream, data);
            writeStream.Close();

 

posted @ 2019-07-16 13:46  zebra_彬  阅读(4230)  评论(0编辑  收藏  举报