C# 如何序列化对象以生成子对象列表?
有以下C# 如何序列化对象以生成子对象列表?,c#,xml,serialization,C#,Xml,Serialization,有以下XML: <X> <Y att="true">FOO</Y> <Y att="false">BAR</Y> <Y att="true">TEST</Y> </X> 福 酒吧 试验 我如何在C 35;中创建可序列化类来序列化并生成一个XML,就像上面的XML一样 请记住,我无法创建更多的标记,我需要准确地生成这些XML序列化对象。如果您只需要一个类,就很容易了。我将您
XML
:
<X>
<Y att="true">FOO</Y>
<Y att="false">BAR</Y>
<Y att="true">TEST</Y>
</X>
福
酒吧
试验
我如何在C 35;
中创建可序列化类来序列化并生成一个XML
,就像上面的XML
一样
请记住,我无法创建更多的标记,我需要准确地生成这些
XML
序列化对象。如果您只需要一个类,就很容易了。我将您的xml粘贴到
这是结果
/*
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0
*/
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="Y")]
public class Y {
[XmlAttribute(AttributeName="att")]
public string Att { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName="X")]
public class X {
[XmlElement(ElementName="Y")]
public List<Y> Y { get; set; }
}
}
/*
根据Apache许可证2.0版获得许可
http://www.apache.org/licenses/LICENSE-2.0
*/
使用制度;
使用System.Xml.Serialization;
使用System.Collections.Generic;
名称空间Xml2CSharp
{
[XmlRoot(ElementName=“Y”)]
公共Y类{
[XmlAttribute(AttributeName=“att”)]
公共字符串Att{get;set;}
[XmlText]
公共字符串文本{get;set;}
}
[XmlRoot(ElementName=“X”)]
公共X类{
[XmlElement(ElementName=“Y”)]
公共列表Y{get;set;}
}
}
如果您只需要一个类,那么这很容易。我将您的xml粘贴到
这是结果
/*
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0
*/
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="Y")]
public class Y {
[XmlAttribute(AttributeName="att")]
public string Att { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName="X")]
public class X {
[XmlElement(ElementName="Y")]
public List<Y> Y { get; set; }
}
}
/*
根据Apache许可证2.0版获得许可
http://www.apache.org/licenses/LICENSE-2.0
*/
使用制度;
使用System.Xml.Serialization;
使用System.Collections.Generic;
名称空间Xml2CSharp
{
[XmlRoot(ElementName=“Y”)]
公共Y类{
[XmlAttribute(AttributeName=“att”)]
公共字符串Att{get;set;}
[XmlText]
公共字符串文本{get;set;}
}
[XmlRoot(ElementName=“X”)]
公共X类{
[XmlElement(ElementName=“Y”)]
公共列表Y{get;set;}
}
}
将[xmlement(“Y”)]
属性应用于所有类?将[xmlement(“Y”)]
属性应用于所有类?非常感谢,我不知道XmlText
属性。我很高兴我帮了忙:)@只有好奇的是,一个更好的设计将Y.Att
作为bool
并且不需要任何进一步的修改谢谢,我不知道XmlText
属性。我很高兴我帮了忙:)@只有好奇的是,更好的设计将Y.Att
作为bool
并且不需要任何进一步的修改