c# - 如何使用动态标签名称将数组序列化为 XML
问题描述
我需要在 C# 上使用动态标记名称将一组对象序列化为 XML。我创建了两个需要序列化为 xml 的类,但我不知道如何创建具有动态名称的标签。
例如,我有以下课程:
[System.Xml.Serialization.XmlRootAttribute(IsNullable = false)]
public class GeneralInformation
{
private Info[] addInfoList;
/// <remarks/>
[System.Xml.Serialization.XmlArray("InfoList")]
public Info[] AddInfoList
{
get
{
return this.addInfoList;
}
set
{
this.addInfoList = value;
}
}
}
public class Info
{
private string infoMessage;
/// <remarks/>
[System.Xml.Serialization.XmlElement("InfoName")]
public string InfoMessage
{
get
{
return this.infoMessage;
}
set
{
this.infoMessage = value;
}
}
}
如果我添加一些简单的数据并将其序列化,我会得到:
<?xml version="1.0" encoding="utf-16"?>
<GeneralInformation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InfoList>
<Info>
<InfoName>Test1</InfoName>
</Info>
<Info>
<InfoName>Test2</InfoName>
</Info>
<Info>
<InfoName>Test3</InfoName>
</Info>
</InfoList>
</GeneralInformation>
但是我需要用数组的索引+ 1 来枚举标签“Info”。这可能吗?结果看起来像这样。
<?xml version="1.0" encoding="utf-16"?>
<GeneralInformation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InfoList>
<Info001>
<InfoName>Test1</InfoName>
</Info001>
<Info002>
<InfoName>Test2</InfoName>
</Info002>
<Info003>
<InfoName>Test3</InfoName>
</Info003>
</InfoList>
</GeneralInformation>
注意我只需要将我的序列化为GeneralInformation
XML,而不是反序列化。
解决方案
使用 XDocument :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication45
{
class Program
{
static void Main(string[] args)
{
string xmlIdent = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
"<GeneralInformation xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"</GeneralInformation>";
XDocument doc = XDocument.Parse(xmlIdent);
XElement generalInfo = doc.Root;
XElement infoList = new XElement("InfoList");
generalInfo.Add(infoList);
for (int i = 0; i < 10; i++)
{
infoList.Add(new XElement("Infor" + i.ToString("0##"), new XElement("InfoName", "Test" + i.ToString("0##"))));
}
}
}
}
//<?xml version="1.0" encoding="utf-16"?>
//<GeneralInformation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
// <InfoList>
// <Info001>
// <InfoName>Test1</InfoName>
// </Info001>
// <Info002>
// <InfoName>Test2</InfoName>
// </Info002>
// <Info003>
// <InfoName>Test3</InfoName>
// </Info003>
// </InfoList>
//</GeneralInformation>
推荐阅读
- powershell - 如何使用 azcopy 将文件夹永久同步到 Azure Blobstore?
- reactjs - 为 window.onstorage 移除事件监听器?
- php - 如何在laravel中三个模型的pivot中部署关系?
- android - 未解决的参考导入 kotlinx.android 和 androidx.preference?
- php - Laravel 通知和邮件组件报错
- javascript - 如何将样式属性作为路由存储在变量中?
- composer-php - Laravel 8 中损坏的 composer.json 文件
- python - 如何在pygame中获取文本宽度?
- ruby-on-rails - 重启脚本以启动 Rails 服务器
- javascript - Axios.post TypeError:无法读取未定义的属性“0”