如何在C#中将包含其他类列表的类列表转换为XML

时间:2018-08-08 09:44:45

标签: c# xml oop collections

我有一个Class对象列表。

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并保存到文本文件。请注意,此类不可序列化。

1 个答案:

答案 0 :(得分: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>