无法将 XML 转换为 C# SOAP Web 服务方法中的输入字符串

问题描述 投票:0回答:1

我的任务是编写一个 C# SOAP Web 服务,用于将数据从 JSON 格式转换为 XML 格式并返回。我已经实现了该服务和两种方法。从 JSON 到 XML 的转换方法已经可以使用。 然而,我在从 XML 转换为 JSON 时遇到了问题。我无法将输入 XML 解析为该方法所需的字符串。由于 XML 中存在属性,因此无法解释 XML。有人可以帮忙吗?

这是我的 XML 到 JSON 方法

public string ConvertXMLToJSON(string InputXMLData) {
    try {
      //Interprets the Input String into a XML File    
      var InterpretedXML = XDocument.Parse(InputXMLData);

     //Converts the Interpreted XML using the JSON Convert Funktion 
      string OutputJSONData = JsonConvert.SerializeXNode(InterpretedXML);

      return OutputJSONData;

       //Filter out any Exception   
    } catch (Exception ex) {
      Console.WriteLine(ex.Message);
      return $"Error while converting XML to JSON: {ex.Message}";
    }
  }

这也是我的 SOAP 请求示例

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
    <soapenv:Header/>
    <soapenv:Body>
        <tem:ConvertXMLToJSON>
            <tem:InputXMLData>
<?xml version="1.0" encoding="UTF-8"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>
            </tem:InputXMLData>
        </tem:ConvertXMLToJSON>
    </soapenv:Body>
</soapenv:Envelope>

我已经尝试使用动态变量重新定义该方法,但没有成功。我还尝试将方法的输入字符串定义为文字字符串,但这也不起作用。

c# json xml soap
1个回答
0
投票

您的服务期望 InputXMLData 作为字符串。因此,您要么需要传递 CDATA,要么转义输入数据。

C数据:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
    <soapenv:Header/>
    <soapenv:Body>
        <tem:ConvertXMLToJSON>
            <tem:InputXMLData>
<![CDATA[<?xml version="1.0" encoding="UTF-8"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>]]>
            </tem:InputXMLData>
        </tem:ConvertXMLToJSON>
    </soapenv:Body>
</soapenv:Envelope>

逃脱:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
    <soapenv:Header/>
    <soapenv:Body>
        <tem:ConvertXMLToJSON>
            <tem:InputXMLData>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;note&gt;&lt;to&gt;Tove&lt;/to&gt;&lt;from&gt;Jani&lt;/from&gt;&lt;heading&gt;Reminder&lt;/heading&gt;&lt;body&gt;Don&apos;t forget me this weekend!&lt;/body&gt;&lt;/note&gt;
            </tem:InputXMLData>
        </tem:ConvertXMLToJSON>
    </soapenv:Body>
</soapenv:Envelope>
© www.soinside.com 2019 - 2024. All rights reserved.