首页 > 解决方案 > 意外的 XML 声明。XML 声明必须是文档中的第一个节点

问题描述

我正在尝试使用 HttpUtility.Decode 以正确的格式获取我的 xml 响应。在 Xml 文档中执行并加载它时,它会引发以下异常:意外的 XML 声明。XML 声明必须是文档中的第一个节点,并且它之前不允许出现空白字符。第 1 行,位置 313。我不知道为什么,因为如果我没记错的话,xml 声明确实显示为第一个节点。我对 XML 相当陌生,因此我们将不胜感激。我该如何解决?谢谢。

XML 解码响应:

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><Query_With_StringResponse xmlns="http://www.syspro.com/ns/query/"><Query_With_StringResult><?xml version="1.0" encoding="Windows-1252"?>
<ARListOfCustomers Language='05' Language2='EN' CssStyle='' DecFormat='1' DateFormat='01' Role='01' Version='7.0.005' OperatorPrimaryRole='   '   >
<QueryOptions>
<ReportSequence>CU</ReportSequence>
<PriceCode/>
<PriceProductmatrix>N</PriceProductmatrix>
<ExtraFields>N</ExtraFields>
<InterestExemptionStatusSelection>A</InterestExemptionStatusSelection>
<TaxExemptionSelection>A</TaxExemptionSelection>
<CustomerSelectionFilterType>A</CustomerSelectionFilterType>
<CustomerSelectionFilterValue/>
<CustomerClassSelectionFilterType>A</CustomerClassSelectionFilterType>
<CustomerClassSelectionFilterValue/>
<GeographicAreaSelectionFilterType>A</GeographicAreaSelectionFilterType>
<GeographicAreaSelectionFilterValue/>
<BranchSelectionFilterType>A</BranchSelectionFilterType>
<BranchSelectionFilterValue/>
<SalespersonSelectionFilterType>A</SalespersonSelectionFilterType>
<SalespersonSelectionFilterValue/>
<LineDiscountCodeSelectionFilterType>A</LineDiscountCodeSelectionFilterType>
<LineDiscountCodeSelectionFilterValue/>
<TermsSelectionFilterType>A</TermsSelectionFilterType>
<TermsSelectionFilterValue/>
<ProductCategorySelectionFilterType>A</ProductCategorySelectionFilterType>
<ProductCategorySelectionFilterValue/>
<InvoiceDiscountCodeSelectionFilterType>A</InvoiceDiscountCodeSelectionFilterType>
<InvoiceDiscountCodeSelectionFilterValue/>
<CurrencySelectionFilterType>A</CurrencySelectionFilterType>
<CurrencySelectionFilterValue/>
<CreditLimitSelectionFilterType>A</CreditLimitSelectionFilterType>
<CreditLimitSelectionFilterValue/>
</QueryOptions>
<Customer>
<CustomerListHeader>
<Customer>TSAR</Customer>
<CustomerName>TSAR BUSINESS SOLUTION</CustomerName>
<CustomerShortName>TSAR BUSINESS SOLUTI</CustomerShortName>
<Branch>TSAR</Branch>
<BranchDescription>HEAD OFFICE  TSAR</BranchDescription>
<Geography>031</Geography>
<GeographyDescription>DURBAN</GeographyDescription>
<Class/>
<ClassDescription>** Not on file **</ClassDescription>
<BalanceType>Op-item</BalanceType>
<Sales>IVAN</Sales>
<CreditLimit>           0</CreditLimit>
<Currency>R</Currency>
<CurrencyDescription>Rand</CurrencyDescription>
<Telephone/>
<InvoiceTermsCode>CO</InvoiceTermsCode>
<TermsCodeDescription>CASH ON DELIVERY</TermsCodeDescription>
</CustomerListHeader>
<CustomerListDetails>
<Contact/>
<TaxNo>Tax No:</TaxNo>
<SpecialInstructions/>
<SoldToAddress1/>
<SoldToAddress2/>
<SoldToAddress3/>
<SoldToAddress3Loc/>
<SoldToAddress4/>
<SoldToAddress5/>
<SoldToAddress6/>
<SoldToGpsLat>  0.000000</SoldToGpsLat>
<SoldToGpsLong>   0.000000</SoldToGpsLong>
<ShipToAddress1>STRAUSS DALY</ShipToAddress1>
<ShipToAddress2>41 RICHFONT CRICLE</ShipToAddress2>
<ShipToAddress3>DURBAN</ShipToAddress3>
<ShipToAddress3Loc/>
<ShipToAddress4>KZB</ShipToAddress4>
<ShipToAddress5>SOUTH AFRICA</ShipToAddress5>
<ShipToAddress6>4000</ShipToAddress6>
<ShipToGpsLat>  0.000000</ShipToGpsLat>
<ShipToGpsLong>   0.000000</ShipToGpsLong>
<GSTNumber/>
<LineDiscCode/>
<InvDiscCode/>
<DefaultPriceCode/>
<CompanyTaxNumber/>
<ExemptFinChg>No finance charges</ExemptFinChg>
</CustomerListDetails>
</Customer>
<ReportSummary>
<NoOfCustomersListed>    1</NoOfCustomersListed>
</ReportSummary>
</ARListOfCustomers>
 </Query_With_StringResult></Query_With_StringResponse></soap:Body></soap:Envelope>

我的代码:doc.LoadXml(decodedXml) ;”上的代码中断

 public async Task<string> CreateSoapEnvelop()
        {
            string soapString = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                <soap:Body>
                 <Query_With_String xmlns=""http://www.syspro.com/ns/query/"">
                <UserId>" + Settings.GUID + @"</UserId>
                <BusinessObject></BusinessObject>
                <XMLIn></XMLIn>
                </Query_With_String>
                </soap:Body>
            </soap:Envelope>";
            try
            {
                HttpResponseMessage response = await PostXmlRequest("http://sysprowebservices/query.asmx", soapString);
                var soapResponse = await response.Content.ReadAsStringAsync();


                var decodedXml = HttpUtility.HtmlDecode(soapResponse);

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(decodedXml);

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
                nsmgr.AddNamespace("ab", "http://www.syspro.com/ns/query/");
                nsmgr.AddNamespace("bg", " https://bixg.choicepoint.com/webservices/3.0");
                nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
                nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

                XmlNode xmlnode = doc.DocumentElement.SelectSingleNode("/soap:Envelope/soap:Body/ab:Query_With_StringResponse/ab:Query_With_StringResult", nsmgr);

                string customer = xmlnode.SelectSingleNode("CustomerName").InnerText;
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
            return "";
        }

        public static async Task<HttpResponseMessage> PostXmlRequest(string baseUrl, string xmlString)
        {
            using (var httpClient = new HttpClient())
            {
                var httpContent = new StringContent(xmlString, Encoding.UTF8, "text/xml");
                httpContent.Headers.Add("SOAPAction", "http://www.syspro.com/ns/query/Query_With_String");

                return await httpClient.PostAsync(baseUrl, httpContent);

            }
        }

更新

{
                HttpResponseMessage response = await PostXmlRequest("http://196.37.159.30/sysprowebservices/query.asmx", soapString);
                var soapResponse = await response.Content.ReadAsStringAsync();


                XmlDocument doc = new XmlDocument();
                doc.LoadXml(soapResponse);


                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
                nsmgr.AddNamespace("ab", "http://www.syspro.com/ns/query/");
                nsmgr.AddNamespace("bg", " https://bixg.choicepoint.com/webservices/3.0");
                nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
                nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

                XmlNode xmlnode = doc.DocumentElement.SelectSingleNode("/soap:Envelope/soap:Body/ab:Query_With_StringResponse/ab:Query_With_StringResult", nsmgr);
                var xmlDecoded = HttpUtility.HtmlDecode(xmlnode.ToString());


            }

更新来自 XmlDecode 的响应:“System.Xml.XmlElement”

标签: c#xmlsoap

解决方案


首先,除非您非常清楚自己在做什么,否则不要推出您自己的 SOAP 客户端。你不能改用WCF吗?

但是您有一个返回... XML 的SOAP 调用。您不能只将整个响应解码为 HTML,因为这样会丢失内部 XML 的编码,从而导致无效的 XML 文档。

您需要先阅读响应,然后获取内部 XML 字符串,然后对其进行解码:

XmlDocument doc = new XmlDocument();
doc.LoadXml(soapResponse);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("ab", "http://www.syspro.com/ns/query/");
nsmgr.AddNamespace("bg", " https://bixg.choicepoint.com/webservices/3.0");
nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

XmlNode xmlnode = doc.DocumentElement.SelectSingleNode("/soap:Envelope/soap:Body/ab:Query_With_StringResponse/ab:Query_With_StringResult", nsmgr);

现在xmlnode保存编码的 XML。解码并做任何你想做的事:

var decodedXml = HttpUtility.HtmlDecode(xmlnode.InnerXml);

推荐阅读