You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# SOAP WebService问题:无法解析含属性的XML为方法输入字符串

解决C# SOAP WebService中XML转JSON的解析问题

问题分析

核心问题在于SOAP请求传递的XML字符串携带了XML声明(<?xml version="1.0" encoding="UTF-8"?>),或XML内容在SOAP信封中未正确转义,导致XDocument.Parse无法正常解析输入字符串。当XML包含属性时,未转义的引号会破坏SOAP信封结构,进一步导致传递给方法的InputXMLData格式无效。

解决方案

1. 调整解析逻辑,清理输入XML

修改ConvertXMLToJSON方法,先移除XML声明(避免解析冲突),同时使用合适的解析选项处理XML内容:

public string ConvertXMLToJSON(string InputXMLData) {
    try {
        // 移除开头的XML声明,避免解析时的格式冲突
        var cleanedXml = System.Text.RegularExpressions.Regex.Replace(InputXMLData, @"^<\?xml.*?\?>", string.Empty).Trim();
        
        // 解析XML,保留空白字符避免格式丢失
        var interpretedXml = XDocument.Parse(cleanedXml, LoadOptions.PreserveWhitespace);

        // 序列化XML到JSON,可选格式化输出提升可读性
        string outputJson = JsonConvert.SerializeXNode(interpretedXml, Formatting.Indented);

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

2. 修正SOAP请求中的XML转义规则

当传递包含属性的XML时,必须确保XML中的特殊字符(如<、>、")在SOAP信封中正确转义:

错误示例(未转义属性引号):

<tem:InputXMLData>
<note id="123"><to>Tove</to>...</note>
</tem:InputXMLData>

正确示例(转义后):

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
    <soapenv:Header/>
    <soapenv:Body>
        <tem:ConvertXMLToJSON>
            <tem:InputXMLData>
&lt;note id=&quot;123&quot;&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't forget me this weekend!&lt;/body&gt;&lt;/note&gt;
            </tem:InputXMLData>
        </tem:ConvertXMLToJSON>
    </soapenv:Body>
</soapenv:Envelope>

3. 调试建议

  • 在方法开头添加日志,输出实际收到的InputXMLData内容,确认是否存在截断、转义错误或多余字符
  • 先传递无属性的简化XML,验证基础转换逻辑正常后再逐步添加属性测试

内容的提问来源于stack exchange,提问作者Elias Giannopoulos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 08:44:59