将XDocument中的嵌套类遍历为JSON

时间:2019-05-14 12:32:36

标签: c# http linq-to-xml

在C#API中,我收到一个XML响应,我需要将其转换为JSON才能返回到我的前端客户端应用程序。我不太清楚如何将嵌套后代转换为嵌套类。

我在下面截断了两个C#类。

public class DetailsKey
{
  public string Status {get; set;}
  public string ErrorMessage {get; set;}
  public string AmountApproved {get; set;}
  public PaymentDetails PaymentDetails {get; set;}
}

public class PaymentDetails
{
  public string Id {get;set;}
  public string PaymentType {get;set;}
  public string Customer {get;set;}
}

收到回复后,我将其解析如下:

XDocument xd = XDocument.Parse(result);

var detResponse = xd.Descendants().Where(x => x.Name.LocalName == "DetailsKey").Select(x => new DetailsKey()
{
  Status = (string)x.Element(x.Name.Namespace + "Status"),
  ErrorMessage = (string)x.Element(x.Name.Namespace + "ErrorMessage"),
  AmountApproved = (string)x.Element(x.Name.Namespace + "AmountApproved"),
  PaymentDetails = x.Descendants("PaymentDetails").Select(p => new PaymentDetails()
   {
     PaymentDetail = x.Descendants("PaymentDetail").Select(pd => new PaymentDetail(){
       Id = (string)pd.Element(pd.Name.Namespace + "Id"),
       ErrorMessage = (string)pd.Element(pd.Name.Namespace + "ErrorMessage"),
       PaymentType = (string)pd.Element(pd.Name.Namespace + "PaymentType"),
       Customer = (string)pd.Element(pd.Name.Namespace + "Customer")
       }).FirstOrDefault(),
    }).FirstOrDefault(),
 }).FirstOrDefault();

如果我注释掉“ PaymentDetails = ...”,则没有错误。但是,当我尝试解析PaymentDetails后代时,我得到了错误。解析后代并将其放入嵌套类的正确方法是什么?

以下是XML的示例:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<DetailsKey>
  <Status>APPROVED</Status>
  <AmountApproved>7.65</AmountApproved>
  <ErrorMessage/>
  <PaymentDetails>
   <PaymentDetail>
    <Id>12345</Id>
    <ErrorMessage/>
    <PaymentType>SALE</PaymentType>
    <Customer>John Smith</Customer>
   </PaymentDetail>
  </PaymentDetails>
</DetailsKey>
</soap:Body>
</soap:Envelope>

1 个答案:

答案 0 :(得分:0)

有两个问题。首先,正如在第一条评论中建议的@mahlatse一样,我需要将firstOrDefault()添加到每个嵌套后代中。一旦添加,错误就消除了。但是我仍然得到嵌套后代的空值。

第二个解决方案包括添加:

.Where(x => x.Name.LocalName == "nameofElement")

在Select调用之前,并在Descendants()中消除nameOfElement字符串。

一旦修复,就可以将xml转换为JSON。