【问题标题】:List Collection XML Serialization列表集合 XML 序列化
【发布时间】:2011-07-13 11:28:21
【问题描述】:

我一直在研究 xml 序列化,但在序列化列表集合时遇到了问题。我想序列化一个列表集合,而不用上层元素环绕它。请参见下面的示例:

结果序列化:

<?xml version="1.0" encoding="utf-8" ?>
<Person>
  <Name>John</Name>
  <AddressLine>
    <string>Line 1</string>
    <string>Line 2</string>
    <string>Line 3</string>
  </AddressLine>
  <Telephone>123456789</Telephone>
</Person>

我要输出的序列化是:

<?xml version="1.0" encoding="utf-8" ?>
<Person>
  <Name>John</Name>
  <AddressLine>Line 1</AddressLine>
  <AddressLine>Line 2</AddressLine>
  <AddressLine>Line 3</AddressLine>
  <Telephone>123456789</Telephone>
</Person>

我已经尝试为我要序列化的类设置不同的属性,但我似乎无法使用它。如果有人能告诉我我需要使用哪些属性来使我的 xml 序列化看起来像我想要的输出 xml,那将不胜感激。

干杯!

【问题讨论】:

    标签: c# .net xml serialization xml-serialization


    【解决方案1】:
    [Serializable]
    public class Person
    {
        public string Name { get; set; }
    
        [XmlElement]
        public List<string> AddressLine { get; set; }
    }
    

    产生所需的输出:

    <?xml version="1.0"?>
    <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Name>John</Name>
      <AddressLine>1</AddressLine>
      <AddressLine>2</AddressLine>
      <AddressLine>3</AddressLine>
    </Person>
    

    【讨论】:

    • 感谢您的帮助。我不认为你可以用 xml 属性将元素名设置为空来解释序列化程序对该属性的影响?
    • @madness800,你可以只设置[XmlElement]而不初始化ElementName
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多