从多个类生成XML?

时间:2012-03-23 12:17:16

标签: c# .net xml

我还有另外一个关于让我的XML序列化整洁的问题,我似乎无法做到这一点。我的配置文件如下:

namespace SMCProcessMonitor
{
[Serializable()]
[XmlRoot("Email-Settings")] 
     public class Config
{     
         [XmlElement("Recipient")]
         public string recipient;
         [XmlElement("Server-port")]
         public int serverport;
         [XmlElement("Username")]
         public string username;
         [XmlElement("Password")]
         public string password;
         [XmlElement("Program")]
         public List<Programs> mPrograms = new List<Programs>();
         public string serialId;
     }

     public class Email
    {

             public string Recipient
             {
                 get
                 {
                     return SMCProcessMonitor.ConfigManager.mConfigurations.recipient;
                 }
                 set
                 {
                     SMCProcessMonitor.ConfigManager.mConfigurations.recipient = value;
                 }
             }

             public int ServerPort
             {
                 get
                 {
                     return SMCProcessMonitor.ConfigManager.mConfigurations.serverport;
                 }
                 set
                 {
                     SMCProcessMonitor.ConfigManager.mConfigurations.serverport = value;
                 }
             }
             public string Username
             {
                 get
                 {
                     return SMCProcessMonitor.ConfigManager.mConfigurations.username;
                 }
                 set
                 {
                     SMCProcessMonitor.ConfigManager.mConfigurations.username = value;
                 }
             }
        public string Password { get; set; }

    }
         [Serializable()]
    public class Programs
{
        [XmlElement("Filename")] public string mFileName { get; set; }
        [XmlElement("Filepath")]public string mFilePath { get; set; }
}

         public class Database
         {
             public string mSerial { get; set; }
         }
         }

理想情况下,我想要做的是让这三个类(电子邮件设置,数据库和程序)中的每一个都有自己的标签,如此

<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<email-settings>
  <Recipient>sadh</Recipient>
  <Server-port>23</Server-port>
  <Username>lkms</Username>
  <Password>kmkdvm</Password>
</email-settings>
<Program>
  <Filename>MerlinAlarm.exe</Filename>
  <Filepath>D:\Merlin\Initsys\Merlin\Bin\MerlinAlarm.exe</Filepath>
</Program>
<database-settings>
  <serialId>1</serialId>
</database-settings>
</Config>

但我得到了类似于此的东西:

 <Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <Recipient>blah</Recipient>
 <Server-port>1111</Server-port>
 <Username>blah</Username>
 <Password>blah</Password>
 <Program>
 <Filename>chrome.exe</Filename>
 <Filepath>
 C:\Users\Shane\AppData\Local\Google\Chrome\Application\chrome.exe
 </Filepath>
 </Program>
 <serialId>1234</serialId>
 </Config>

很抱歉这是一个麻烦,但这是我现在做的事情,我确定这里有一些基本的逻辑,我在这里找不到......任何人都可以给我一些关于如何以我指定的格式获取此XML的指示以上? 谢谢,谢恩。

编辑:我的序列化类。

 namespace SMCProcessMonitor
{
public class ShanesXMLserializer
{
    private string  mFileAndPath;
    public Config   mConfigurations = null;
    public Config mConfigurationsProgram = null;



    public ShanesXMLserializer(string inFileAndPath)
    {
        mFileAndPath    = inFileAndPath;
        mConfigurations = new Config();

    }

    public bool Write()
    {
        try
        {
            XmlSerializer x = new XmlSerializer(mConfigurations.GetType());
            StreamWriter writer = new StreamWriter(mFileAndPath);
            x.Serialize(writer, mConfigurations);
            writer.Close();
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Exception found while writing: " + ex.Message);
        };

        return false;
    }

    public bool Read()
    {
        try
        {
            XmlSerializer x = new XmlSerializer(typeof(Config));
            StreamReader reader = new StreamReader(mFileAndPath);
            mConfigurations = (Config)x.Deserialize(reader);
            reader.Close();
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Exception found while reading: " + ex.Message);
        };

        return false;
    }

    public Config GetConfigEmail
    {
        get
        {
            return mConfigurations;
        }
    }


}

}

编辑2: 我的新配置文件: @Craig - 我正在使用这个配置文件,就像你说的那样但我仍然没有得到所需的XML,在我的配置类之后显示。

           using System;
           using System.Collections.Generic;
           using System.Linq;
           using System.Xml.Serialization;
           using System.Text;

命名空间SMCProcessMonitor {     [序列化()]

     public class Config
{     

         public string recipient;
         public int serverport;
         public string username;
         public string password;
         public List<Programs> mPrograms = new List<Programs>();
         public string serialId;
    [XmlElement("email-settings")]
         public Email Email { get; set; }
         public Programs Programs { get; set; }
     [XmlElement("database-settings")]
         public Database Database { get; set; }


     }

     public class Email
    {
         [XmlElement("Recipient")]
         public string Recipient { get; set; }
            [XmlElement("Server-port")]
         public int ServerPort { get; set; }
         [XmlElement("Username")]
         public string Username { get; set; }
         [XmlElement("Password")]
         public string Password { get; set; }

    }
         [Serializable()]
    public class Programs
    {
        [XmlElement("Filename")] public string mFileName { get; set; }
        [XmlElement("Filepath")]public string mFilePath { get; set; }
    }

    public class Database
    {
        [XmlElement("SerialID")]
        public string mSerial { get; set; }
    }
    }

但我还是得到了:

  <Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <recipient>shane</recipient>
  <serverport>23</serverport>
  <username>oid</username>
  <password>jidj</password>
  <mPrograms/>
  </Config>

2 个答案:

答案 0 :(得分:1)

这将为您提供所需的输出:

public class Config
{
    [XmlElement("email-settings")]
    public Email Email { get; set; }

    public Program Program { get; set; }

    [XmlElement("database-settings")]
    public Database Database { get; set; }
}

public class Email
{
    public string Recipient { get; set; }

    [XmlElement("Server-port")]
    public int ServerPort { get; set; }

    public string Username { get; set; }
    public string Password { get; set; }
}

public class Program
{
    public string Filename { get; set; }

    public string Filepath { get; set; }
}

public class Database
{
    public string serialId { get; set; }
}

这是一个控制台应用程序,它将对象序列化为文件并生成您正在寻找的确切XML。只需将其复制并粘贴到控制台应用程序中,然后从那里取出即可。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new Config
            {
                Email = new Email
                {
                    Recipient = "sadh",
                    ServerPort = 23,
                    Username = "lkms",
                    Password = "kmkdvm"
                },
                Program = new Programs
                {
                    Filename = "MerlinAlarm.exe",
                    Filepath = @"D:\Merlin\Initsys\Merlin\Bin\MerlinAlarm.exe"
                },
                Database = new Database
                {
                    serialId = "1"
                }
            };

            XmlSerializer serializer = new XmlSerializer(typeof(Config));

            var textWriter = new StreamWriter(@"C:\config.xml");
            serializer.Serialize(textWriter, config);
            textWriter.Close();

            Console.Read();
        }
    }

    #region [Classes]

    public class Config
    {
        [XmlElement("email-settings")]
        public Email Email { get; set; }

        public Programs Program { get; set; }

        [XmlElement("database-settings")]
        public Database Database { get; set; }
    }

    public class Email
    {
        public string Recipient { get; set; }

        [XmlElement("Server-port")]
        public int ServerPort { get; set; }

        public string Username { get; set; }
        public string Password { get; set; }
    }

    public class Programs
    {
        public string Filename { get; set; }

        public string Filepath { get; set; }
    }

    public class Database
    {
        public string serialId { get; set; }
    }

    #endregion
}

答案 1 :(得分:0)

我将在这里建议一个完全横向的方法,只是为了简单和维护。

如果您使用源XML文件并生成XSD架构,该怎么办?

例如:

xsd.exe MyXMLFile1.xml

这将生成XML模式文件(MyXMLFile1.xsd)。获取模式并生成类(再次使用xsd.exe):

xsd.exe /c MyXMLFile1.xsd

这将生成一个可保证的可序列化POCO,您可以继续使用它。类名和属性可能与您当前的POCO中的名称和属性不匹配,但生成预期的XML,以及从XML反序列化。

额外的好处是,向前,您只需要修改源XML文件,然后运行这两个命令来维护POCO。

希望有帮助...