如何在 c# 中对列表进行类包装以进行 xml 序列化

一个类如何在 c# 中包装一个列表以进行 xml 序列化?我想添加一个根。也许类包装器不是一个好主意。我应该使用不同的方法吗?


当我序列化以下类时:


public class Parts

{

    //main class   

    [XmlElement("Access")]

    public List<Access> AccessDB = new List<Access>

    {

        new Access

        {

            Items = new[] {

             new Component { Name = "dbName" }

            ,new Component { Name = "DbElement" } }

            , Scope = "GlobalVariable", UId = "21"

        },


        new Access

        {

            Items = new[] {

             new Component { Name = "TagName" } }

            , Scope = "GlobalVariable", UId = "22"

        }

    };


}

我得到:


<Parts>

  <Access Scope="Scope" UId="21">

    <Symbol>

      <Component Name="Name" />

      <Component Name="Name" />

    </Symbol>

  </Access>

  <Access Scope="Scope" UId="22">

    <Symbol>

      <Component Name="Name" />

    </Symbol>

  </Access>

  <Part Name="PartName" UId="23" />

</Parts>

但我需要的是:


<myroot>

    <Parts>

      <Access Scope="Scope" UId="21">

        <Symbol>

          <Component Name="Name" />

          <Component Name="Name" />

        </Symbol>

      </Access>

      <Access Scope="Scope" UId="22">

        <Symbol>

          <Component Name="Name" />

        </Symbol>

      </Access>

      <Part Name="PartName" UId="23" />

    </Parts>

</myroot>

非常欢迎任何建议!


芜湖不芜
浏览 97回答 2
2回答

临摹微笑

如果myroot元素只需要出现在xml输出中,您可以在序列化期间添加它。使用XmlWriteras 输出目标进行序列化。在序列化Parts实例之前,您使用XmlWriter创建myroot元素。XmlWriterSettings settings = new XmlWriterSettings { Indent = true&nbsp; };StringBuilder stringBuilder = new StringBuilder();using (var xmlWriter = XmlWriter.Create(stringBuilder, settings)){&nbsp; &nbsp; xmlWriter.WriteStartElement("myroot"); // Writes <myroot>&nbsp; &nbsp; var serializer = new XmlSerializer(typeof(Parts));&nbsp; &nbsp; var parts = new Parts();&nbsp; &nbsp; serializer.Serialize(xmlWriter, parts);&nbsp; &nbsp; xmlWriter.WriteEndElement(); // Writes </myroot>}

湖上湖

我发现也可以对其他类进行类包装,但是该类的实例必须是公共的。在代码中:public class myRoot&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public Parts Parts = new Parts();&nbsp; &nbsp; }然后序列化类myRoot
打开App,查看更多内容
随时随地看视频慕课网APP