C#XmlSerializer生成错误的XML字符串

时间:2014-01-16 16:55:30

标签: c# xml

我使用以下代码将我的类序列化为XML字符串:

AXMLItem rc = new AXMLItem();

rc.Attributes.Add(new Reports.ReportConfiguration.Questionnaire.FormObjectXMLItem.Attribute { Value = "ddddd" });

MemoryStream fw = new MemoryStream();

var serializer = new XmlSerializer(typeof(AXMLItem ));

        using (StringWriter textWriter = new StringWriter())
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
            {
                serializer.Serialize(xmlWriter, rc);
            }
            string myString = textWriter.ToString(); //This is the output as a string
        }    

那个班级定义

 [XmlType(TypeName = "A")]
 public class AXMLItem
 {
        [XmlType(TypeName = "B")]
        public List<Attr> Attrs { get; set; }

        [XmlType(TypeName = "C")]
        public class Attr
        {
            [XmlText]
            public string Value { get; set; }
        }

        public AXMLItem()
        {
             Attrs = new List<Attr>();
        }
 }

给了我以下字符串

    <?xml version="1.0" encoding="utf-16"?>
    <A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <B>
           <C>ddddd</C>
        </B>
    </A>

但我需要

    <?xml version="1.0" encoding="utf-16"?>
    <A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <C>ddddd</C>
    </A>

明白可能有很多<C>...</C>个项目。如何解决?

1 个答案:

答案 0 :(得分:6)

只需在集合属性中添加XmlElement属性:

    [XmlElement("C")]
    public List<Attr> Attrs { get; set; }