c#xml序列化

时间:2010-11-24 16:30:35

标签: c#

如何反序列化这样的XML,我在Message Array中遇到了一些问题。

<EventSources>
<Source>
 <Event>
  <Id>9</Id> 
  <Message LcId="1033">Text9</Message> 
  <Message LcId="1031">Message 9</Message> 
  <Message LcId="1034">Text9</Message> 
 </Event>

 <Event>
  <Id>10</Id> 
  <Message LcId="1033">Text10</Message> 
  <Message LcId="1031">Message 10</Message> 
  <Message LcId="1034">Text10</Message> 
 </Event>

</Source>
</EventSources>

我尝试序列化此代码但输出不匹配

public class EventSources
{
    #region Variables
    private List<Event> _Source = new List<Event>();
    #endregion

    #region Properties
    public List<Event> Source
    {
        get { return _Source; }
        set { _Source = value; }
    }


    #endregion

    public EventSources() { }

    public void AddError(Event error)
    {
        _Source.Add(error);
    }
}

public class Event
{
    #region Variables
    private int _Id;
    private List<Message> _languageEntries = new List<Message>();
    #endregion

    #region Properties
    [XmlElement()]
    public int Id
    {
        get { return _Id; }
        set { _Id = value; }
    }

    public List<Message> LanguageEntries
    {
        get { return _languageEntries; }
        set { _languageEntries = value; }
    }
    #endregion

    public Event() { }

    public Event(int id)
    {
        _Id = Id;
    }

    public void Add(Message entry)
    {
        _languageEntries.Add(entry);
    }
}

public class Message
{
    #region Variables
    private string _lang = string.Empty;
    private string _text = string.Empty;
    #endregion

    #region Properties

    [XmlAttribute("LcId")]
    public string LcId
    {
        get { return _lang; }
        set { _lang = value; }
    }

    [XmlText]
    public string Text
    {
        get { return _text; }
        set { _text = value; }
    }
    #endregion

    public Message() { }

    }
}

输出:

<EventSources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Source>
    <Event>
      <Id>5</Id>
      <LanguageEntries>
        <Message LcId="5">kjhfdkgdskfkgds</Message>
        <Message LcId="554">kjhfskfkgds</Message>
      </LanguageEntries>
    </Event>
  </Source>
  <Messages />
</EventSources>

2 个答案:

答案 0 :(得分:2)

[XmlElement("Message")]
public List<Message> LanguageEntries
{
    get { return _languageEntries; }
    set { _languageEntries = value; }
}

答案 1 :(得分:0)

如果您有此xml的架构文件,请使用xsd.exe生成匹配的C#对象。一旦生成了XML模式的对象表示,就可以使用XmlSerializer类中的方法来序列化和反序列化XML文件。