Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用C将命名类列表转换为XML元素的子元素?_C#_Xml_Serialization - Fatal编程技术网

C# 使用C将命名类列表转换为XML元素的子元素?

C# 使用C将命名类列表转换为XML元素的子元素?,c#,xml,serialization,C#,Xml,Serialization,给定以下XML块: <stuff> <items> <thing1>stuff</thing1> <thing1>blah</thing1> <thing2>meh ..</thing2> <thing1>again</thing1> </items> </stuff> 如何定义ListOfStuff使其工作 顺

给定以下XML块:

<stuff>
  <items>
    <thing1>stuff</thing1>
    <thing1>blah</thing1>
    <thing2>meh ..</thing2>
    <thing1>again</thing1>
  </items>
</stuff>
如何定义ListOfStuff使其工作

顺便说一句,这似乎是我试图解决的简化问题,因为我已经让序列化很好地工作了,对于第一件和第二件事情,它正在寻找一种方法,将许多不同类型的东西1和东西2放入XML中,根据消息的不同,我确实有大约30个东西需要序列化到XML中。我敢肯定我以前见过这样做,看起来是这样的:

public class thing1 { //handle members of the XML here no sweat }
public class thing2 { //handle members of the XML here no sweat }

public class stuff { public ListOfStuff items { get; set; } }
[SomeAttribute(typeof(thing1))]
[SomeAttribute(typeof(thing2))]
public class ListOfStuff {
}

但我不知道那到底是什么样子,这正是我想弄明白的。那么,蹩脚的标题,蹩脚的问题,似曾相识,是吗?

为什么不解析xml,继续使用反射(即Activator.CreateInstance方法)创建对象,并将其放在一个包含一列stuff的ListOfStuff中,其中包含一列stuff对象,其中包含一列stuff对象,假设thing1和thing2派生自things类。。明白了吗?

我假设您使用的是所谓的XML序列化,即System.XML.Serialization命名空间中的XmlSerializer类

将这些属性放在items属性上:

    [XmlArray]
    [XmlArrayItem(typeof(thing1))]
    [XmlArrayItem(typeof(thing2))]

我通常更喜欢使用DataContractSerializer和KnownTypeAttribute。但在您的情况下,由于您使用的是XmlSerializer,所以可以尝试使用XmlIncludeAttribute


链接:

因为我在本地使用C XmlSerialization,而不是自己解析XML。根据我的经验,任何人自己解析XML都是自找麻烦。你是在寻找KnownTypeAttribute吗@Kassem有一个同样适用于Xml序列化而不是DCS的吗?@Kassem-好主意,但我认为KnownTypeAttribute对于处理多态性非常有用,它可以识别派生自基类型的已知类型,但对这种情况没有影响。你可能是对的。但在我看来,因为它们都是items节点的子节点,所以让它们都派生自itemsbase类或类似的东西是有意义的。对不起,伙计们,正当我准备测试这两种方法时,有人告诉我,为什么不处理我告诉过你忽略的低优先级问题?所以我会在明早中环给你回电话。