修改xml配置文件的结果是一行文件

本文关键字:一行 文件 xml 配置文件 结果是 修改 | 更新日期: 2023-09-27 18:05:34

我有一个程序,允许用户打开xml文件并编辑它们,然后保存它们。问题是,当我打开一个配置文件,(.exe.config),它保存和覆盖正确,但整个文件失去了格式,成为一个巨大的,长,单行。当然,在我的程序中,用户永远不会看到它是一行,所以它不是我的程序功能的主要问题,但是有人知道如何保持配置xml文件的格式吗?当我打开它时,我只是简单地改变设定值,仅此而已。据我所知,我没有对格式/缩进做任何改动。或者对它为什么这样做有一些见解?

多谢!

Tf.rz

编辑:下面是代码:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
using System.Xml;
namespace WindowsFormsApplication4
{
    public partial class ProgramConfig : Form
    {
        public ProgramConfig()
        {
            InitializeComponent();
        }
        private XmlDocument m_XmlDoc;
        private FileStream fIn;
        private StreamReader sr;
        private StreamWriter sw;
        private OrderedDictionary m_Settings;
        private int m_savecounter = 0;
        private void ProgramConfig_Load(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = "File open: " + GatewayConfiguration.Properties.Settings.Default.Config;
                int index = 0;
                loadconfigfile(GatewayConfiguration.Properties.Settings.Default.Config);
                string[] keys = new string[m_Settings.Keys.Count];
                m_Settings.Keys.CopyTo(keys, 0);
                string[] values = new string[m_Settings.Values.Count];
                m_Settings.Values.CopyTo(values, 0);
                BindingList<KeyValueType> list = new BindingList<KeyValueType>();
                for (index = 0; index < m_Settings.Count; index++)
                {
                    list.Add(new KeyValueType(keys[index], values[index].ToString()));
                }
                dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
                dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
                dataGridView1.Columns[0].Name = "Key";
                dataGridView1.Columns[0].DataPropertyName = "key";
                dataGridView1.Columns[1].Name = "Value";
                dataGridView1.Columns[1].DataPropertyName = "value";
                var source = new BindingSource();
                source.DataSource = list;
                dataGridView1.DataSource = source;
                for (index = 0; index < dataGridView1.Columns.Count; index++)
                {
                    // Auto resize while keeping user resize true.
                    dataGridView1.Columns[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    int initialAutoSizeWidth = dataGridView1.Columns[index].Width;
                    dataGridView1.Columns[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
                    dataGridView1.Columns[index].Width = initialAutoSizeWidth;
                }
                dataGridView1.ReadOnly = false;
                dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
                dataGridView1.Columns[2].Name = "New Value";
            }
            catch (Exception ex)
            {
                textBox1.Text = ex.Message;
            }
        }
        private void loadAppSettings()
        {
            m_Settings = new OrderedDictionary();
            XmlNodeList nl = m_XmlDoc.GetElementsByTagName("setting");
            foreach (XmlNode node in nl)
            {
                try
                {
                    m_Settings.Add(node.Attributes["name"].Value, node.ChildNodes[0].InnerText);
                }
                catch (Exception)
                {
                }
            }
        }
        public void loadconfigfile(string configfile)
        {
            if (File.Exists(configfile))
            {
                m_XmlDoc = new XmlDocument();
                GatewayConfiguration.Properties.Settings.Default.Config = configfile;
                GatewayConfiguration.Properties.Settings.Default.Save();
                fIn = new FileStream(configfile, FileMode.Open, FileAccess.ReadWrite);
                sr = new StreamReader(fIn);
                sw = new StreamWriter(fIn);
                try
                {
                    m_XmlDoc.LoadXml(sr.ReadToEnd());
                    m_XmlDoc.PreserveWhitespace = true;
                    loadAppSettings();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                throw new FileNotFoundException(configfile + " does not exist.");
            }
        }
        private void SaveAppSettings_Click(object sender, EventArgs e)
        {
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result = MessageBox.Show("Overwrite the old values with the new values?", "Save Settings?", buttons);
            if (result == DialogResult.No)
            {
                return;
            }
            int index = 0;
            string[] keys = new string[m_Settings.Keys.Count];
            m_Settings.Keys.CopyTo(keys, 0);
            for (index = 0; index < dataGridView1.Rows.Count; index++)
            {
                if ((string)dataGridView1[2, index].Value != string.Empty)
                {
                    setAppSetting(keys[index], (string)dataGridView1[2, index].Value);
                }
            }
            textBox1.Text = "Settings Saved. You may now exit.";
            m_savecounter++;
            dataGridView1.Update();
            dataGridView1.Refresh();
        }
        public void setAppSetting(string name, string newValue)
        {
            if (!m_Settings.Contains(name))
            {
                throw new Exception(String.Format("Setting {0} does not exists in {1}", name, GatewayConfiguration.Properties.Settings.Default.Config));
            }
            else
            {
                if (newValue == null || m_Settings[name].ToString() == newValue)
                {
                    return;
                }
                m_Settings[name] = newValue;
                m_XmlDoc.SelectSingleNode("//setting[@name='" + name + "']").ChildNodes[0].InnerXml = newValue;
                fIn.SetLength(0);
                sw.Write(m_XmlDoc.InnerXml);
                sw.Flush();
            }
        }
        public class KeyValueType
        {
            private string _key;
            public string Key
            { 
                get 
                {
                    return _key;
                }
            }
            private string _value;
            public string Value
            {
                get
                {
                    return _value;
                }
            }
            public KeyValueType(string key, string value)
            {
                _key = key;
                _value = value;
            }
        }
        private void ProgramConfig_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_savecounter == 0)
            {
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                DialogResult result = MessageBox.Show("You have not saved, still want to exit?", "Exit?", buttons);
                if (result == DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
            sw.Close();
            sr.Close();
            fIn.Close();
        }
    }
}

修改xml配置文件的结果是一行文件

如果您正在使用XmlDocument,您可以将PreserveWhitespace属性设置为true -如果未设置,则默认为false。

XDocument的等效是Load()LoadOptions.PreserveWhitespace的过载。