将xml deserlize扩展为动态子元素

时间:2017-12-14 06:30:21

标签: c# xml api

我的要求是调用Api并从Api获取响应并保存到db。响应是xml格式。但是同样的Api调用我得到 2种类型的xml 就像这样

  

APi批准回复

<Message>
<Body>
<PaResponse>
<Approved>
</Approved>
</Paresponse>
</Body>
</Message> 
  

来自Api的Decliened响应

<Message>
<Body>
<PaResponse>
<Decliened>
</Decliened>
</Paresponse>
</Body>
</Message> 
  

我的模型类

class Message{

  public Body Body {get;set;}

}
class Body{
 public Paresponse PaResponse { get;set;}
}

class PaResponse{

//here is the proplem i need choose dynamically for this child object
public Approved {get;set;}

//public Decliened {get;set;}


}

但是如何识别要动态去除的子元素

  

现在我使用此扩展方法来确定已批准的请求。

public static T DeserializeObject<T>(this string xml)
                    where T : new()
 {
                    if (string.IsNullOrEmpty(xml))
                    {
                        return new T();
                    }
                    try
                    {
                        using (var stringReader = new StringReader(xml))
                        {
                            var serializer = new XmlSerializer(typeof(T));
                            return (T)serializer.Deserialize(stringReader);
                        }
                    }
                    catch (Exception ex)
                    {
                        return new T();
                    }


  }

注意:Api仅提供Xml格式没有json

1 个答案:

答案 0 :(得分:1)

你的解决方案是正确的;您无需选择,而您的班级PaResponse应该包含ApprovedDeclined两个字段。当你的xml反序列化时,这些字段中的一个将具有不同于null的值,而另一个将具有空值。您可以检查它们以了解您的响应。

XML

<?xml version="1.0" encoding="utf-8" ?>
<Message>
  <Body>
    <PaResponse>
      <Approved>
      </Approved>
      <Decliened>
      </Decliened>
    </PaResponse>
    </Body>
</Message>

复制该XML并从Visual Studio菜单中选择编辑 - &gt;选择性粘贴 - &gt;将XML粘贴为类

然后,Visual Studio将为您创建模型。在你的情况下,它们是简单的模型,你之前已经想过它们。

然后使用简单的C#代码进行反序列化

// I just saved the xml to a file, in your case 
// you will read it from the API
string path = @"G:\Projects\StackOverFlow\WpfApp1\Message.xml";
FileStream reader = File.OpenRead(path);
XmlSerializer ser = new XmlSerializer(typeof(Message));
Message message = (Message)ser.Deserialize(reader);