如何在XML数组中添加根元素?

时间:2018-10-30 16:42:04

标签: c# xml

我想将类反序列化为XML documnet。我有:

public partial class CurveType : AbstractCurveType {

    private AbstractCurveSegmentType[] segmentsField;

    /// <remarks/>
    [ XmlElement(Type = typeof(ArcType)),
      XmlElement(Type = typeof(CircleType)),
      XmlElement(Type = typeof(LineStringSegmentType), ElementName = "LineStringSegment")]
    public AbstractCurveSegmentType[] segments {
        get {
            return this.segmentsField;
        }
        set {
            this.segmentsField = value;
        }
    }
}

因此segments可以包含类型ArcTypeCircleTypeLineStringSegmentType的对象。

现在它反序列化于:

 <gml:Curve>
   <gml:LineStringSegment>
    ***
   </gml:LineStringSegment>
 </gml:Curve>

但是我想看看:

  <gml:Curve>
   <gml:segments>
      <gml:LineStringSegment>
        ***
      </gml:LineStringSegment>
   </gml:segments>
 </gml:Curve>

当我删除注释XmlElement时,我得到了<gml:segments>,但在这种情况下,所有<gml:LineStringSegment>都变成了<gml:AbstractCurveSegmentType type='LineStringSegment'>

如何添加此<gml:segments>根元素?

1 个答案:

答案 0 :(得分:2)

您可以尝试创建另一个充当包装器的类:

[XmlRoot(ElementName = "Curve")]
public class ObjectModel {
    [XmlElement(ElementName = "segments")]
    public CurveType CurveTypes {get; set;}
}

然后初始化对象并序列化它们:

AbstractCurveSegmentType[] arr = new AbstractCurveSegmentType[] 
{
    new ArcType { Id = 1, ArcTypeName = "arcTypeName"},
    new CircleType { Id = 2, CircleTypeName = "circleTypeName"}
};


var obj = new ObjectModel
{
    CurveTypes = new CurveType { segments = arr }
};

var xml = Xml.Serialize(obj);

这是序列化的帮助方法:

public class Xml
{
    public static string Serialize<T>(T obj)
        {
            var xmlSerializer = new XmlSerializer(obj.GetType());
            using (var textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, obj);
                return textWriter.ToString();
            }
        }
}

您将获得以下xml:

<Curve>
  <segments>
    <ArcType>
      <Id>1</Id>
      <ArcTypeName>arcTypeName</ArcTypeName>
    </ArcType>
    <CircleType>
      <Id>2</Id>
      <CircleTypeName>circleTypeName</CircleTypeName>
    </CircleType>
  </segments>
</Curve>