我正在尝试从C#中的类型生成XML输出。我正在使用MvcContrib XmlResult类,我在其中包含了一个链接。
作为一个简单的测试,看看我是否可以使它工作,我使用以下代码:
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);
(将2种类型定义为:)
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; }
}
生成此输出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>
我想知道是否可以拥有ID&amp;名称标签在TopTenShareClass
节点中显示为属性,而不是节点本身?理想情况下,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 Name='a'></TopTenShareClass>
<TopTenShareClass Id=2 Name='b'></TopTenShareClass>
<TopTenShareClass Id=3 Name='c'></TopTenShareClass>
</ShareClasses>
</TopTen>
作为参考,XmlResult定义可在此处获得:http://mvccontrib.codeplex.com/SourceControl/changeset/view/5f542a2e51e9#src%2fMVCContrib%2fActionResults%2fXmlResult.cs
答案 0 :(得分:2)
我想它只是使用XmlSerializer
来实现,所以:
public class TopTenShareClass
{
[XmlAttribute]
public int Id { get; set; }
[XmlAttribute]
public string Name { get; set; }
}
完整列表位于MSDN上:Attributes That Control XML Serialization
举个例子,我实在期待:
<TopTenShareClass Id="1" Name="a"/>
<TopTenShareClass Id="2" Name="b"/>
<TopTenShareClass Id="3" Name="c"/>
答案 1 :(得分:1)
您可以控制XML序列化过程using attributes:
public class TopTenShareClass
{
[XmlAttribute]
public int Id { get; set; }
[XmlAttribute]
public string Name { get; set; }
}