修改xml配置文件会生成一个行文件

时间:2011-08-15 20:18:35

标签: c# xml

我有一个程序,允许用户打开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();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

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

XDocument的等效内容是Load()重载LoadOptions.PreserveWhitespace