How to produce XML with attributes rather than nodes, using MvcContrib's XmlResult?

旧城冷巷雨未停 提交于 2019-12-12 19:25:25

问题


I'm trying to generate an XML output from a type in C#. I'm Using the MvcContrib XmlResult class, which I've included a link to below.

As a simple test to see if I could get it working, I'm using the following code:

var topTen = new TopTen
{
    PerformanceTo = DateTime.Now,
    ShareClasses = new List<TopTenShareClass>()
                        {
                            new TopTenShareClass{Id = 1, Name = "a"},
                            new TopTenShareClass{Id = 2, Name = "b"},
                            new TopTenShareClass{Id = 3, Name = "c"}

                        }
};

return new XmlResult(topTen);

(with the 2 types defined as:)

public class TopTen
{
    public DateTime PerformanceTo { get; set; }
    public List<TopTenShareClass> ShareClasses { get; set; }
}

public class TopTenShareClass
{
    public int Id { get; set; }
    public string Name { get; set; }
}

to produce this output XML

<?xml version="1.0" encoding="utf-8"?>
<TopTen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PerformanceTo>2011-02-22T10:56:41.3094548+00:00</PerformanceTo>
  <ShareClasses>
    <TopTenShareClass>
      <Id>1</Id>
      <Name>a</Name>
    </TopTenShareClass>
    <TopTenShareClass>
      <Id>2</Id>
      <Name>b</Name>
    </TopTenShareClass>
    <TopTenShareClass>
      <Id>3</Id>
      <Name>c</Name>
    </TopTenShareClass>
  </ShareClasses>
</TopTen>

I'm wondering if it's possible to have the ID & Name tags appear as attributes in the TopTenShareClass node, rather than nodes themselves? Ideally the XML would be like:

<?xml version="1.0" encoding="utf-8"?>
<TopTen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PerformanceTo>2011-02-22T10:56:41.3094548+00:00</PerformanceTo>
  <ShareClasses>
    <TopTenShareClass Id=1 Name='a'></TopTenShareClass>
    <TopTenShareClass Id=2 Name='b'></TopTenShareClass>
    <TopTenShareClass Id=3 Name='c'></TopTenShareClass>
  </ShareClasses>
</TopTen>

For reference, the XmlResult definition is available here: http://mvccontrib.codeplex.com/SourceControl/changeset/view/5f542a2e51e9#src%2fMVCContrib%2fActionResults%2fXmlResult.cs


回答1:


You could control the XML serialization process using attributes:

public class TopTenShareClass
{
    [XmlAttribute]
    public int Id { get; set; }

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


来源:https://stackoverflow.com/questions/5077308/how-to-produce-xml-with-attributes-rather-than-nodes-using-mvccontribs-xmlresu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!