C# - Parse Soap response to extract data - c#

I am new to C# Soap Web Service. I am able to make a Soap Request. But not sure how to parse the soap response below to get OrderId for example.
<?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>
<OrderCreateByChannelResponse
xmlns="http://retailexpress.com.au/">
<OrderCreateByChannelResult>
<Response
xmlns="">
<OrderCreate>
<Customer>
<Result>Success</Result>
<ExternalCustomerId>170</ExternalCustomerId>
<CustomerId>300941</CustomerId>
</Customer>
<Order>
<Result>Success</Result>
<ExternalOrderId>INT_3673_ccv_20190926132240</ExternalOrderId>
<OrderId>19-00033544</OrderId>
<ChannelID>1</ChannelID>
</Order>
<OrderItems>
<OrderItem>
<Result>Success</Result>
<ExternalOrderItemId></ExternalOrderItemId>
<ProductId>126659</ProductId>
<OrderId>19-00033544</OrderId>
</OrderItem>
</OrderItems>
<OrderPayments>
<OrderPayment>
<Result>Success</Result>
<Amount>23.45</Amount>
<MethodId>38</MethodId>
<OrderId>19-00033544</OrderId>
</OrderPayment>
</OrderPayments>
</OrderCreate>
</Response>
</OrderCreateByChannelResult>
</OrderCreateByChannelResponse>
</soap:Body>
</soap:Envelope>
Any help will be greatly appreciated.
With the below sample code I was able to parse simple XML
string testXML1 = #"<OrderCreateByChannelResult><Response xmlns=""""><OrderCreate><Customer><Result>Success</Result><ExternalCustomerId>170</ExternalCustomerId><CustomerId>300940</CustomerId></Customer></OrderCreate></Response></OrderCreateByChannelResult>";
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.LoadXml(testXML1);
XmlNodeList result = xdoc.SelectNodes("/OrderCreateByChannelResult/Response/OrderCreate/Customer");
foreach (XmlNode xn in result)
{
string ExternalCustomerId = xn["ExternalCustomerId"].InnerText;
Response.Write("ExternalCustomerId = " + ExternalCustomerId);
}
But the moment I include <OrderCreateByChannelResponse xmlns=""http://retailexpress.com.au/""> in the XML string doesn't work.

Try like this
XDocument doc = XDocument.Parse(testXML1);
XNamespace ns = doc.Root.GetDefaultNamespace();
string ExternalCustomerId="";
string CustomerId="";
foreach (XElement element in doc.Descendants(ns + "ExternalCustomerId"))
{
ExternalCustomerId = element.Value;
}
foreach (XElement element in doc.Descendants(ns + "CustomerId"))
{
CustomerId = element.Value;
}

Related

Unable to parse xml string using Xdocument and Linq

I would like to parse the below xml using XDocument in Linq.
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">
<Sources>
<Item>
<Id>1</Id>
<Name>John</Name>
</Item>
<Item>
<Id>2</Id>
<Name>Max</Name>
</Item>
<Item>
<Id>3</Id>
<Name>Ricky</Name>
</Item>
</Sources>
</string>
My parsing code is :
var xDoc = XDocument.Parse(xmlString);
var xElements = xDoc.Element("Sources")?.Elements("Item");
if (xElements != null)
foreach (var source in xElements)
{
Console.Write(source);
}
xElements is always null. I tried using namespace as well, it did not work. How can I resolve this issue?
Try below code:
string stringXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><string xmlns=\"http://tempuri.org/\"><Sources><Item><Id>1</Id><Name>John</Name></Item><Item><Id>2</Id><Name>Max</Name></Item><Item><Id>3</Id><Name>Ricky</Name></Item></Sources></string>";
XDocument xDoc = XDocument.Parse(stringXml);
var items = xDoc.Descendants("{http://tempuri.org/}Sources")?.Descendants("{http://tempuri.org/}Item").ToList();
I tested it and it correctly shows that items has 3 lements :) Maybe you used namespaces differently (it's enough to inspect xDoc objct in object browser and see its namespace).
You need to concatenate the namespace and can directly use Descendants method to fetch all Item nodes like:
XNamespace ns ="http://tempuri.org/";
var xDoc = XDocument.Parse(xmlString);
var xElements = xDoc.Descendants(ns + "Item");
foreach (var source in xElements)
{
Console.Write(source);
}
This prints on Console:
<Item xmlns="http://tempuri.org/">
<Id>1</Id>
<Name>John</Name>
</Item><Item xmlns="http://tempuri.org/">
<Id>2</Id>
<Name>Max</Name>
</Item><Item xmlns="http://tempuri.org/">
<Id>3</Id>
<Name>Ricky</Name>
</Item>
See the working DEMO Fiddle

Read element from SOAP message

I'm trying to read the APP_DATE element in this xml message. Tried using LINQ but unable to read MyResult
<?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>
<MyResponse xmlns="http://tempuri.org/">
<MyResult>
<APP_TYPE>I</APP_TYPE>
<APP_NO>152240</APP_NO>
<APP_DATE>10/03/2016</APP_DATE>
</MyResult>
</MyResponse>
</soap:Body>
</soap:Envelope>
Can't be sure because you didn't supply any example code but I assume you struggle because of the namespaces. So try this:
XmlDocument doc = new XmlDocument();
doc.Load("data.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
ns.AddNamespace("x", "http://tempuri.org/");
var result = doc.SelectSingleNode("//soap:Envelope/soap:Body/x:MyResponse/x:MyResult/x:APP_DATE", ns).InnerText;
For deeper understanding you can read this question
Using Linq it will be like this:
var result = XDocument.Load("data.xml").Root
.Descendants(XName.Get("APP_DATE", "http://tempuri.org/"))
.FirstOrDefault()?.Value;
See how in both examples I have to specify the namespaces of what I'm looking for

how to use soap response and get the xml values in C#

<?xml version="1.0" encoding="UTF-16"?>
<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><GetXmlDocumentResponse xmlns="http://tempuri.org/">
<GetXmlDocumentResult>
<SNR_JO_POST xmlns="">
<Sectors>
<LawyerName> abc</LawyerName>
<ID>{B263A7B1-D766-4308-B486-C63BE66F4D74}</ID>
<Email>abc#gmail.com</Email>
</Sectors>
</SNR_JO_POST>
</GetXmlDocumentResult>
</GetXmlDocumentResponse>
</soap:Body>
</soap:Envelope>
the above is soap response , I want to get values of LawyerName , ID and Email from the response .
How could i use this response in my c# code .
You can use Linq To Xml for this
var xDoc = XDocument.Parse(xmlstring);
var sectors = xDoc.Descendants("Sectors").FirstOrDefault();
var lawyerName = (string)sectors.Element("LawyerName");
var id = (string)sectors.Element("ID");

How to get a node from xml with c#- what am I doing wrong?

Namespaces and XML are still confusing the hell out of me.
Here is my XML (that comes from a SOAP request)
<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>
<MyResponse xmlns="http://tempuri.org/">
<OutputXML xmlns="http://tempuri.org/XMLSchema.xsd">
<Result>
<OutputXML>
<Result>
<Foo>
<Bar />
</Foo>
</Result>
</OutputXML>
</Result>
</OutputXML>
</MyResponse>
</soap:Body>
</soap:Envelope>
I am trying to extract the actual XML part from the SOAP response (starting with the Foo element):
var nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("", "http://tempuri.org/");
nsmgr.AddNamespace("", "http://tempuri.org/XMLSchema.xsd");
var xml = document.DocumentElement
.SelectSingleNode("Foo", nsmgr)
.InnerXml;
But SelectSingleNode returns null. I've tried some different variations on this but can't get anything working. What am I not understanding?
Try this one:
var nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("aaa", "http://tempuri.org/XMLSchema.xsd");
var xml = document.DocumentElement
.SelectSingleNode("aaa:Foo", nsmgr)
.InnerXml;
this is because of Default namespaces has no perfix.
You can use GetElementsByTagName to use namespace uri directly:
var xml = document.GetElementsByTagName("Foo",
"http://tempuri.org/XMLSchema.xsd")[0].InnerXml;
You can use LINQ to XML to get your result, also specify the namespace
XDocument document = XDocument.Load("test.xml");
XNamespace ns = "http://tempuri.org/XMLSchema.xsd";
var test = document.Descendants(ns + "Foo").FirstOrDefault();
Or if you don't want to specify NameSpace then:
var test2 = document.Descendants()
.Where(a => a.Name.LocalName == "Foo")
.FirstOrDefault();

Help with SelectSingleNode, XML and C#

I have the following SOAP 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>
<ABRSearchByABNResponse xmlns="http://abr.business.gov.au/ABRXMLSearch/">
<ABRPayloadSearchResults>
<request>
<identifierSearchRequest>
<identifierType>ABN</identifierType>
<identifierValue>79 142 357 604</identifierValue>
</identifierSearchRequest>
</request>
<response>
<dateRegisterLastUpdated>2011-04-26</dateRegisterLastUpdated>
<dateTimeRetrieved>2011-04-26T14:10:17.8169921+10:00</dateTimeRetrieved>
<businessEntity>
<recordLastUpdatedDate>2010-03-05</recordLastUpdatedDate>
<ABN>
<identifierValue>79142357604</identifierValue>
<isCurrentIndicator>Y</isCurrentIndicator>
<replacedIdentifierValue xsi:nil="true" />
<replacedFrom>0001-01-01</replacedFrom>
</ABN>
<entityStatus>
<effectiveTo>0001-01-01</effectiveTo>
</entityStatus>
<entityType>
<entityTypeCode>PUB</entityTypeCode>
</entityType>
<mainBusinessPhysicalAddress>
<stateCode>NSW</stateCode>
<postcode>2000</postcode>
</mainBusinessPhysicalAddress>
</businessEntity>
</response>
</ABRPayloadSearchResults>
</ABRSearchByABNResponse>
</soap:Body>
</soap:Envelope>
What I am trying to get is the entityTypeCode but I have no success. I tried with
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(searchPayload);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable);
nsmgr.AddNamespace("c", "http://abr.business.gov.au/ABRXMLSearch/");
XmlNode entityTypeCode = xDoc.SelectSingleNode("//entityTypeCode", nsmgr);
and various xpath expressions but it the xmlnode entityTypeCode is always null.
Suggestions?
Thanks in advance.
use XmlNode entityTypeCode = xDoc.SelectSingleNode("//c:entityTypeCode", nsmgr); as you have added the namespace of the element as c prefix in the namespace manager.

Categories

Resources