将 0-n 个元素序列化到另一个元素内
我有两个这样的类:
public class Product
{
public string Name { get; set; }
public int Id { get; set; }
}
public class Category
{
public string CategoryName { get; set; }
public List<Product> Products { get; set; }
}
有什么方法可以在 Category 类上装饰我的 Products 属性,以便它像这样序列化吗?
<Container>
<Category>
<CategoryName>Unicorn Stuff</CategoryName>
<Product>
<Id>1212</Id>
<Name>Unicorn Dust</Name>
</Product>
<Product>
<Id>1829</Id>
<Name>Horn Extension</Name>
</Product>
<Product>
<Id>27373</Id>
<Name>Facemask with hole</Name>
</Product>
</Category>
<Category>
<CategoryName>Pixie</CategoryName>
<Product>
<Id>222</Id>
<Name>Pixie Dust</Name>
</Product>
</Category>
</Container>
请注意,每个类别都有类别元素(类别名称)和 0- n 产品子元素。
...或者我是否必须以更手动的方式生成文档?
(这不是我设计 xml 结构的方式,但是嘿 - 我们生活在一个不完美的世界)
I have two classes like this:
public class Product
{
public string Name { get; set; }
public int Id { get; set; }
}
public class Category
{
public string CategoryName { get; set; }
public List<Product> Products { get; set; }
}
Is there some way I can decorate my Products property on the Category class, so it is serialized like this?
<Container>
<Category>
<CategoryName>Unicorn Stuff</CategoryName>
<Product>
<Id>1212</Id>
<Name>Unicorn Dust</Name>
</Product>
<Product>
<Id>1829</Id>
<Name>Horn Extension</Name>
</Product>
<Product>
<Id>27373</Id>
<Name>Facemask with hole</Name>
</Product>
</Category>
<Category>
<CategoryName>Pixie</CategoryName>
<Product>
<Id>222</Id>
<Name>Pixie Dust</Name>
</Product>
</Category>
</Container>
Note that Each category has category elements (Category name) AND 0-n Product child elements.
...Or do I have to drop down to generating the document in a more manual way?
(This is not how I would have designed the xml structure, but hey - we live in an imperfect world)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
[XmlElement]
属性放在列表上:Place the
[XmlElement]
attribute on the list:我相信 XSD.exe 可以为您从您的班级创建 XSD。然后,您只需使用基本的 XmlSerializer 来序列化到您的 XSD。
或者,您可以创建 XSD,并从 XSD 生成您的类。无论哪种方式都应该有效。
I believe XSD.exe can create the XSD from your class for you. Then you would simply use the basic XmlSerializer to serialize to your XSD.
Alternatively, you can create your XSD, and generate your class from the XSD. Either way should work.