Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/121.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# 序列化/反序列化XML,其中XML元素可以从两个XML元素中选择一个_C#_Xml Serialization - Fatal编程技术网

C# 序列化/反序列化XML,其中XML元素可以从两个XML元素中选择一个

C# 序列化/反序列化XML,其中XML元素可以从两个XML元素中选择一个,c#,xml-serialization,C#,Xml Serialization,在这种情况下,我的xml可以将比如FileWriter或ArgonWriter作为xml元素 例如: <Writer> <FileWriter> <DestinationFolder></DestinationFolder> </FileWriter </Writer> 但在这种情况下,Writer对象中的一个始终为null 有没有什么方法可以为相同的对象编写一个通用代码,而不需要提及两个对象,因为我的根总是只有一个x

在这种情况下,我的xml可以将比如FileWriter或ArgonWriter作为xml元素

例如:

<Writer>
 <FileWriter>
    <DestinationFolder></DestinationFolder>
</FileWriter
</Writer>
但在这种情况下,Writer对象中的一个始终为null

有没有什么方法可以为相同的对象编写一个通用代码,而不需要提及两个对象,因为我的根总是只有一个xml元素???

使用LINQ2XML

XDocument doc=XDocument.Parse(xmlString);
var output=doc.Descendants()
              .Elements()
              .Where(x=>x.Name.LocalName=="FileWriter"||x.Name.LocalName =="HttpWriter")
              .Select(e=>
                   new
                   {
                     Type=e.Name.LocalName.ToString(),
                     Path=(x.Element("DestinationFolder")!=null)
                          ? x.Element("DestinationFolder").Value
                          : x.Element("Url").Value
                   });

现在可以在输出上迭代

foreach(var writer in output)
{
    writer.Type;
    writer.Path;
}

嗨,谢谢你的回复。。我不确定我将在何处编写此逻辑来反序列化我的Xml..我在这里使用XmlSerializer,它使用Xml属性(比如[XmlElement])将对象直接映射到Xml或Xml到对象。。在这种情况下,我正在寻找XmlSerializer自身进行映射的解决方案(你可以说这对我来说是一个限制,而且我们必须遵循当前的内部FWK:()…此外,我上面的示例只是xml的一部分..我有一个大xml和所有其他元素,我能够正确地序列化它。。。
XDocument doc=XDocument.Parse(xmlString);
var output=doc.Descendants()
              .Elements()
              .Where(x=>x.Name.LocalName=="FileWriter"||x.Name.LocalName =="HttpWriter")
              .Select(e=>
                   new
                   {
                     Type=e.Name.LocalName.ToString(),
                     Path=(x.Element("DestinationFolder")!=null)
                          ? x.Element("DestinationFolder").Value
                          : x.Element("Url").Value
                   });
foreach(var writer in output)
{
    writer.Type;
    writer.Path;
}