【问题标题】:How to convert a List of class which contains list of other class in to XML in C#如何在 C# 中将包含其他类列表的类列表转换为 XML
【发布时间】:2018-08-08 09:44:45
【问题描述】:
我有一个类对象列表。
List<SDKReq> SDKReqList = new List<SDKReq>()
SDKReq 类又拥有成员作为类
public class SDKReq
{
public List<String> Identifier { get; set; }
public IDictionary<String, String> Prop { get; set; }
}
我需要将此 List 对象转换为 XML 并保存到文本文件。请注意,这个类是不可序列化的。
【问题讨论】:
标签:
c#
xml
oop
collections
【解决方案1】:
你可以这样做:
public string CreateXml(List<SDKReq> list)
{
//first create the xml declaration
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
//second create a container node for all SDKReq objects
XmlNode SdkListNode = doc.CreateElement("SDKReqList");
doc.AppendChild(SdkListNode);
//iterate through all SDKReq objects and create a container node for each of it
foreach (SDKReq item in list)
{
XmlNode sdkNode = doc.CreateElement("SDKReq");
SdkListNode.AppendChild(sdkNode);
//create a container node for all strings in SDKReq.Identifier
XmlNode IdListNode = doc.CreateElement("Identifiers");
sdkNode.AppendChild(IdListNode);
//iterate through all SDKReq.Identifiers and create a node foreach of it
foreach (string s in item.Identifier)
{
XmlNode idNode = doc.CreateElement("Identifier");
idNode.InnerText = s;
IdListNode.AppendChild(idNode);
}
//create a container node for all SDKReq.Prop
XmlNode propListNode = doc.CreateElement("Props");
sdkNode.AppendChild(propListNode);
//iterate through all SDKReq.Prop and create a node for each of it
foreach (KeyValuePair<string, string> kvp in item.Prop)
{
//since the SDKReq.Prop is a dictionary, you should add both, key and value, to the node.
//i decided to add an attribute 'key' for the key
XmlNode propNode = doc.CreateElement("Prop");
XmlAttribute attribute = doc.CreateAttribute("key");
attribute.Value = kvp.Key;
propNode.Attributes.Append(attribute);
propNode.InnerText = kvp.Value;
propListNode.AppendChild(propNode);
}
}
return doc.InnerXml;
}
我还没有测试过,但是输出应该是这样的:
<?xml version="1.0" encoding="utf-8"?>
<SDKReqList>
<SDKReq>
<Identifiers>
<Identifier>1234</Identifier>
<Identifier>5678</Identifier>
</Identifiers>
<Props>
<Prop key="abc11">Value</Prop>
<Prop key="abc12">Value</Prop>
</Props>
</SDKReq>
<SDKReq>
<Identifiers>
<Identifier>8765</Identifier>
<Identifier>4321</Identifier>
</Identifiers>
<Props>
<Prop key="def22">Value</Prop>
<Prop key="def23">Value</Prop>
</Props>
</SDKReq>
</SDKReqList>