简体   繁体   English

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

[英]C# XmlSerializer generates wrong XML string

I use the following code to serialize my class as XML string: 我使用以下代码将我的类序列化为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
        }    

that class definition 该类的定义

 [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>();
        }
 }

which gives me the following string 这给了我以下字符串

    <?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>

but I need 但是我需要

    <?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>

Keep in ming that there can be many <C>...</C> items. 请记住,可能有很多<C>...</C>项。 How to fix it ? 如何解决?

just add an XmlElement attribute to the collection property: 只需将XmlElement属性添加到collection属性即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM