为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
芜湖不芜 2023-05-14 16:35:46
一个类如何在 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>非常欢迎任何建议!
查看完整描述

2 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

如果myroot元素只需要出现在xml输出中,您可以在序列化期间添加它。

使用XmlWriteras 输出目标进行序列化。

在序列化Parts实例之前,您使用XmlWriter创建myroot元素。


XmlWriterSettings settings = new XmlWriterSettings { Indent = true  };

StringBuilder stringBuilder = new StringBuilder();

using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))

{

    xmlWriter.WriteStartElement("myroot"); // Writes <myroot>


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

    var parts = new Parts();

    serializer.Serialize(xmlWriter, parts);


    xmlWriter.WriteEndElement(); // Writes </myroot>

}


查看完整回答
反对 回复 2023-05-14
?
湖上湖

TA贡献2003条经验 获得超2个赞

我发现也可以对其他类进行类包装,但是该类的实例必须是公共的。在代码中:


public class myRoot

    {

        public Parts Parts = new Parts();

    }

然后序列化类myRoot


查看完整回答
反对 回复 2023-05-14
  • 2 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信