Unexpected XML declaration. The XML declaration must be the first node in the document - c#

I am trying to get my xml response in the correct format using HttpUtility.Decode. Upon doing and loading it in Xml Document, it is throwing the following exception : Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 1, position 313. I'm not sure why because the xml declaration does appear as the first node if I'm not mistaken. Im fairly new to XML so any help will be appreciated. How do I fix this? Thanks.
XML decode response:
<?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>
My code: Code breaks on "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);
}
}
UPDATE
{
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());
}
Update Response from XmlDecode: "System.Xml.XmlElement"

First of all, don't roll your own SOAP client unless you know very well what you're doing. Can't you use WCF instead?
But you have a SOAP call that returns ... XML. You can't just decode the entire response as if it were HTML, because then the encoding of the inner XML will be lost, resulting in an invalid XML document.
You need to read the repsonse first, then obtain the inner XML string and then decode that:
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);
Now xmlnode holds the encoded XML. Decode that and do whatever you want with it:
var decodedXml = HttpUtility.HtmlDecode(xmlnode.InnerXml);

Related

How to get xml response sent to our webpage/url in C#

We would like to ask how to retrieve/get the xml response coming from a third party website. We just supply the redirectUrl and the xml response will be sent to it.
We have tried the code below to retrieve the xml details but it's not retrieving the data.
public ActionResult Index()
{
XmlDocument xdoc = new XmlDocument(); //xml doc used for xml parsing
xdoc.Load("http://xxx/Home/Index");
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("/Data/Quote/Product"); //reading node so that we can traverse thorugh the XML
foreach (XmlNode xNode in xNodelst)//traversing XML
{
Sessions.PartNumber = xNode["PartNum"].InnerText;
}
return View();
}

Data at the root level is invalid. Line 1, position 1. Is it error with the xml format?

Im having a problem with reading my xml with an error of Data at the root level is invalid. Line 1,position 1.
This is my code below:
string soapmessage = response.Content;
XmlDocument xml = new XmlDocument();
xml.LoadXml(soapmessage); //loading soap message as string
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
below attached my XML response

How to pull out of xml-file

Via GET-request I got next xml code:
<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Translation code=\"200\"lang=\"en-ru\"><text>Sample</text></Translation>
So in particular I need to "stretch out" word "Sample". How?
Is this considering as deserialization?
Implemented with next code:
if (response.StatusCode == HttpStatusCode.OK)
{
HttpContent responseContent = response.Content;
var json = await responseContent.ReadAsStringAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(json);
var text = doc.GetElementsByTagName("text")[0].InnerText;
}
Output: Sample

Exclude Result Element in SOAP Call

I'm trying to exclude the result element being returned from my SOAP call but I cant seem to get it excluded. I then set up this simple call which returns xml data from a file. I need the result element removed as it wont validate against the schema. I've tried adding the SoapParameterStyle.Bare but i still get the node
[WebMethod]
[SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElement(IsNullable = true)]
public XmlDocument TestMethod(XmlDocument p_xmlDoc)
{
XmlDocument xmldoc = new XmlDocument();
string sResponsePath = ConfigurationManager.AppSettings["FileDirectory"] + ConfigurationManager.AppSettings["GetOrders"];
string sXMLResponse = File.ReadAllText(sResponsePath);
xmldoc.LoadXml(sXMLResponse);
return xmldoc;
}
Here is the first few nodes that would be returned from that SOAP call and as you can see the TestMethodResult is returned under the Body element:
<?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>
<TestMethodResult xmlns="http://tempuri.org/">
<ns0:TestMethodResponse xmlns:ns0="http://eibdigital.co.uk/citb/EibOrderInterface">
<ns0:TestMethodResult>
You can run simple XSLT transformation on XML. Example program
string xmlInput = #"<?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>
<TestMethodResult xmlns=""http://tempuri.org/"">
<ns0:TestMethodResponse xmlns:ns0=""http://eibdigital.co.uk/citb/EibOrderInterface"">
<ns0:TestMethodResult>
</ns0:TestMethodResult>
</ns0:TestMethodResponse>
</TestMethodResult>
</soap:Body>
</soap:Envelope>";
string xslInput = #"<?xml version=""1.0"" encoding=""UTF-8""?>
<xsl:stylesheet xmlns:xsl=""http://www.w3.org/1999/XSL/Transform""
xmlns:tmp=""http://tempuri.org/""
version=""1.0"">
<!--identity template, copies all content by default-->
<xsl:template match=""#*|node()"">
<xsl:copy>
<xsl:apply-templates select=""#*|node()""/>
</xsl:copy>
</xsl:template>
<!--don't generate content for the <b>, just apply-templates to it's children-->
<xsl:template match=""tmp:TestMethodResult"">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>";
string output = String.Empty;
using (StringReader srt = new StringReader(xslInput))
using (StringReader sri = new StringReader(xmlInput))
{
using (XmlReader xrt = XmlReader.Create(srt))
using (XmlReader xri = XmlReader.Create(sri))
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xrt);
using (StringWriter sw = new StringWriter())
using (XmlWriter xwo = XmlWriter.Create(sw, xslt.OutputSettings))
{
xslt.Transform(xri, xwo);
output = sw.ToString();
}
}
}
And the output at the end contains your xml (without TestMethodResult xmlns="http://tempuri.org/")
This answer was inspired by two other SOF questions:
How do I remove the outermost wrappers using xslt?
How to transform XML as a string w/o using files in .NET?
Also if you one to stick with the XML files loaded from disk you can do it like this:
string sResponsePath = ConfigurationManager.AppSettings["FileDirectory"] + ConfigurationManager.AppSettings["GetOrders"];
string xsltPath = "Drive://your/path/to/xslt/file.xslt";
XPathDocument myXPathDoc = new XPathDocument(sResponsePath);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(xsltPath);
var ms = new MemoryStream();
XmlTextWriter myWriter = new XmlTextWriter(ms, Encoding.UTF8);
myXslTrans.Transform(myXPathDoc, null, myWriter);
ms.Position = 0;
var sr = new StreamReader(ms);
var myStr = sr.ReadToEnd();
compare:
How to apply an XSLT Stylesheet in C#

Why XDocument.Load(url) throws exception?

I am new to C# and I am trying to read xml from URL.
xml looks like this
<posts>
<post>
<title>title1</title>
<des>des1</des>
</post>
<post>
<title>title2</title>
<des>des2</des>
</post>
.....
</posts>
And this is what I am using to parse it.
String uri = "url";
XDocument books = XDocument.Load(uri);
When the debug hits XDocument line it throws an exception and skips it.
How can I avoid this?
I think URI for your XML is lacking the extension of the file which is causing the problem. Please try using:
String uri = PATH + "url.xml";
XDocument books = new XDocument();
books.Load(uri);
To parse XML obtained from URL u can use:
string strURL = "http://<some-server>/<some-uri-path>";
string xmlStr;
WebClient wc = new WebClient();
xmlStr = wc.DownloadString(strURL);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStr);

Categories

Resources