Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store custom application settings in XML

please help. I have this code, it's my class to serialize\deserialize application settings.

[XmlRoot("EvaStartupData")]
[Serializable] 
public class MyConfigClass
{
    public string ServerName { get; set; }
    public string Database { get; set; }
    public string UserName { get; set; }
    public string UserLogin { get; set; }


    public static void MyConfigLoad()
    {
        FileInfo fi = new FileInfo(myConfigFileName);
        if (fi.Exists)
        {
            XmlSerializer mySerializer = new XmlSerializer(myConfigClass.GetType());
            StreamReader myXmlReader = new StreamReader(myConfigFileName);
            try
            {

                myConfigClass = (MyConfigClass)mySerializer.Deserialize(myXmlReader);
                myXmlReader.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show("Ошибка сериализации MyConfigLoad\n" + e.Message);
            }

            finally
            {
                myXmlReader.Dispose();
            }
        }
    }

    public static void MyConfigSave()
    {
        XmlSerializer mySerializer = new XmlSerializer(myConfigClass.GetType());
        StreamWriter myXmlWriter = new StreamWriter(myConfigFileName);
        try
        {
            mySerializer.Serialize(myXmlWriter, myConfigClass);
        }
        catch (Exception e)
        {
            MessageBox.Show("Ошибка сериализации MyConfigSave\n" + e.Message);
        }

        finally
        {
            myXmlWriter.Dispose();
        }
    }

}

Serialization give's me simple xml-structure:

<ServerName>navuhodonoser</ServerName>
<Database>matrix</Database>
<UserName>Mr.Smith</UserName>
<UserLogin>neo</UserLogin>

How must i modify my class to get this xml structure ?:

<Connection ServerName="navuhodonoser" Database="matrix" ....>
like image 520
northernwind Avatar asked Aug 05 '26 04:08

northernwind


1 Answers

By default the XmlSerializer will serialize all public properties as elements; to override that you'll need to tag each property with [XmlAttribute] (from System.Xml.Serialization namespace) which will give you your desired output.

For example:

[XmlAttribute]
public string ServerName { get; set; }

[XmlAttribute]
public string Database { get; set; }

[XmlElement]
public string UserName { get; set; }

// Note: no attribute
public string UserLogin { get; set; }

will produce something like:

<xml ServerName="Value" Database="Value">
    <UserName>Value</UserName>  <!-- Note that UserName was tagged with XmlElement, which matches the default behavior -->
    <UserLogin>Value</UserLogin>
</xml>
like image 157
STW Avatar answered Aug 06 '26 20:08

STW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!