Reading SOAP xml answer - c#

I have to read a SOAP answer from the file below
<?xml version="1.0"?>
<Envelopes>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Body>
<env:Fault>
<env:Code>
<env:Value>env:Receiver</env:Value>
<env:Subcode>
<env:Value>-1</env:Value>
</env:Subcode>
</env:Code>
<env:Reason>
<env:Text xml:lang="en">CServiceData::SetPropertyValue failed; '</env:Text>
</env:Reason>
<env:Detail>
<Object>4</Object>
<ObjectIndex>1</ObjectIndex>
<Command>AddObject</Command>
<SessionID>B8FE2330-4252-4BB1-A3EE-053F4413A0C0</SessionID>
</env:Detail>
</env:Fault>
</env:Body>
</env:Envelope>
</Envelopes>
I only need the content of the Text tag CServiceData::SetPropertyValue failed;

You can use XPath:
public string GetErrorMessage(string xml)
{
using (StringReader sr = new StringReader(xml))
{
var doc = new XPathDocument(sr);
var nav = doc.CreateNavigator();
var xmlNs = new XmlNamespaceManager(nav.NameTable);
xmlNs.AddNamespace("env", #"http://www.w3.org/2003/05/soap-envelope");
var node = nav.SelectSingleNode("//env:Text", xmlNs);
return node.Value;
}
}
or you can use LINQ To XML:
public string GetErrorMessage(string xml)
{
var doc = XDocument.Parse(xml);
var node = doc.Descendants(XName.Get("Text", #"http://www.w3.org/2003/05/soap-envelope"))
.FirstOrDefault();
return node.Value;
}

Related

read xml file on c#, reading the arabic text provide a encrypted string not actual utf-8

xml file-> for example this is hosted on the url http://localhost/test1
<?xml version="1.0" encoding="utf-8"?>
<MSG>
<arabic>
<translationOne>اول</translationOne>
<translationTwo>دوم</translationTwo>
</arabic>
<persian>
<translationOne>یک</translationOne>
<translationTwo>دوم</translationTwo>
</persian>
</MSG>
c# class
var m_strFilePath = "http://localhost/test1";
string xmlStr;
using (var wc = new WebClient())
{
xmlStr = wc.DownloadString(m_strFilePath);
}
var xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlStr);
XmlNodeList unNodeA = xmldoc.SelectNodes("MSG/arabic");
XmlNodeList unNodeP = xmldoc.SelectNodes("MSG/persian");
string arabic = "";
foreach (XmlNode i in unNodeA)
{
arabic += i["translationOne"].InnerText;
}
string persian= "";
string persian2 ="";
foreach (XmlNode ii in unNodeP)
{
persian+= ii["translationOne"].InnerText;
persian2+= ii["translationTwo"].InnerText;
}
->>print(arabic and persian);
here the test contain not correct format like (اول دوم) it's some kind of (عبد العزيز عباسین)
It is better to use LINQ to XML API. It is available in the .Net Framework since 2007.
c#
void Main()
{
XDocument xdoc = XDocument.Parse(#"<?xml version='1.0' encoding='utf-8'?><MSG>
<arabic>
<translationOne>اول</translationOne>
<translationTwo>دوم</translationTwo>
</arabic>
<persian>
<translationOne>یک</translationOne>
<translationTwo>دوم</translationTwo>
</persian>
</MSG>");
foreach (XElement elem in xdoc.Descendants("arabic").Elements())
{
Console.WriteLine("translation: {0}", elem.Value);
}
}
If you need to load XML from the URL:
const string Url = #"http://hurt.super-toys.pl/xml/super_toys_ceneo_pelny.xml";
XDocument xdoc = XDocument.Load(Url);
Output
translation: اول
translation: دوم

XDocument just reads the first title?

I need to parse xml but my code just parses one title not all.
How can I parse part ?
This is my code:
CustomResponse itemCustom = new CustomResponse ();
XDocument response = XDocument.Parse(responseXml);
XElement rootElement = response.Root;
foreach (XElement sellResponse in rootElement.Elements())
{
itemCustom .ErrorCode = sellResponse.Element("ErrorCode").Value;
itemCustom .ErrorMessage = sellResponse.Element("ErrorMessage").Value;
itemCustom .CustomerID= sellResponse.Element("CustomerID").Value;
itemCustom .CustomerType= sellResponse.Element("CustomerType").Value;
}
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<TINS_XML_DATA>
<Header>
<ErrorCode>WAATS</ErrorCode>
<ErrorMessage>UTL</ErrorMessage>
</Header>
<Customer>
<CustomerID>UTL11111111111111111111</CustomerID>
<CustomerType>NSell</CustomerType>
</Customer>
</TINS_XML_DATA>
Try something like this:
foreach (XElement sellResponse in rootElement.Elements())
{
if (sellResponse.Name == "Header")
{
itemCustom.ErrorCode = sellResponse.Element("ErrorCode").Value;
itemCustom.ErrorMessage = sellResponse.Element("ErrorMessage").Value;
}
else if (sellResponse.Name == "Customer")
{
itemCustom.CustomerID = sellResponse.Element("CustomerID").Value;
itemCustom.CustomerType = sellResponse.Element("CustomerType").Value;
}
}
Update: You could also use XPath to find required elements as like below:
var xDoc = new XmlDocument();
xDoc.LoadXml(xml);
var errorMessage = xDoc.SelectNodes("//ErrorMessage")[0].InnerText;
This is my solved:
var xDoc = new XmlDocument();
xDoc.LoadXml(responseXml);
itemSell.ErrorCode = xDoc.SelectNodes("//ErrorCode")[0].InnerText;
itemSell.ErrorMessage = xDoc.SelectNodes("//ErrorMessage")[0].InnerText;
itemSell.CustomerID= xDoc.SelectNodes("//CustomerID")[0].InnerText;

How to update soap xml file element value in c#.net

How can I update the SOAP xml element value from an soap xml file using c#.net? My file is as below:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<Action xmlns="http://www.w3.org/2005/08/addressing">http://extn.ssac.ee.sim.dsh.cms.hhs.gov/SsaCompositePortType/VerifySSAResponse</Action>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:27f0af81-0da7-441f-83a7-fb2beaf30664</MessageID>
<RelatesTo xmlns="http://www.w3.org/2005/08/addressing">uuid:e8dcd685-cb86-400a-8059-dcad985a7ea7</RelatesTo>
</soap:Header>
<soap:Body>
<exch:SSACompositeResponse xmlns:exch="http://ssac.ee.sim.dsh.cms.hhs.gov">
<ssac:SSACompositeIndividualResponse xmlns:ssac="http://extn.ssac.ee.sim.dsh.cms.hhs.gov">
<ssac:ResponseMetadata>
<ssac:ResponseCode>HS000000</ssac:ResponseCode>
<ssac:ResponseDescriptionText>Success</ssac:ResponseDescriptionText>
</ssac:ResponseMetadata>
<ssac:PersonSSNIdentification>199123051</ssac:PersonSSNIdentification>
<ssac:SSAResponse>
<ssac:SSNVerificationIndicator>true</ssac:SSNVerificationIndicator>
<ssac:DeathConfirmationCode>Unconfirmed</ssac:DeathConfirmationCode>
<nc:PersonUSCitizenIndicator xmlns:nc="http://niem.gov/niem/niem-core/2.0">true</nc:PersonUSCitizenIndicator>
<ssac:PersonIncarcerationInformationIndicator>false</ssac:PersonIncarcerationInformationIndicator>
<ssac:SSATitleIIAnnualIncomeInformationIndicator>false</ssac:SSATitleIIAnnualIncomeInformationIndicator>
<ssac:SSATitleIIMonthlyIncomeInformationIndicator>false</ssac:SSATitleIIMonthlyIncomeInformationIndicator>
<ssac:SSAQuartersOfCoverageInformationIndicator>false</ssac:SSAQuartersOfCoverageInformationIndicator>
</ssac:SSAResponse>
</ssac:SSACompositeIndividualResponse>
</exch:SSACompositeResponse>
Here I want to update ssac:PersonSSNIdentification (199123051) value to 9876543210?
XmlNamespaceManager xnm;
xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
var xmlDoc = new XmlDocument();
xmlDoc.Load(newSSAPathName);
XmlNodeList aNodes = xmlDoc.SelectNodes("/Envelope/Body/SSACompositeResponse/SSACompositeIndividualResponse");
foreach (XmlNode aNode in aNodes)
{ var innerXmlNode = aNode.SelectSingleNode("/PersonSSNIdentification");
if (innerXmlNode != null)
{ innerXmlNode.Value = lstSsn[0];
}
}
xmlDoc.Save(newSSAPathName);
But this doesn't work...is there any way...
I'd recommend doing this with LINQ to XML rather than the older XmlDocument API.
First, load your XML into an XDocument:
var doc = XDocument.Load(newSSAPathName);
Then, define an XNamespace for each of the namespaces you have in your XML:
var soap = (XNamespace)"http://www.w3.org/2003/05/soap-envelope";
var exch = (XNamespace)"http://ssac.ee.sim.dsh.cms.hhs.gov";
var ssac = (XNamespace)"http://extn.ssac.ee.sim.dsh.cms.hhs.gov";
Now query for all elements at the required depth in the XML hierarchy with the required fully qualified names:
var ssnIds = doc.Elements(soap + "Envelope")
.Elements(soap + "Body")
.Elements(exch + "SSACompositeResponse")
.Elements(ssac + "SSACompositeIndividualResponse")
.Elements(ssac + "PersonSSNIdentification");
Finally, change the appropriate element value:
foreach (var ssnId in ssnIds)
if (ssnId.Value == "199123051")
ssnId.Value = "9876543210";
Alternatively, if you do want to use an XPATH query, you need to populate an XmlNamespaceManager with all 3 namespaces. The documentation for XPathSelectElements(XNode, String, IXmlNamespaceResolver) shows how to do this. Then use the prefixes you chose corresponding to each namespace in your XPATH query:
using (var reader = XmlReader.Create(newSSAPathName))
{
var doc = XDocument.Load(reader);
// Set up a namespaceManager as described in https://msdn.microsoft.com/en-us/library/bb351355%28v=vs.110%29.aspx
var nameTable = reader.NameTable;
var namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
namespaceManager.AddNamespace("exch", "http://ssac.ee.sim.dsh.cms.hhs.gov");
namespaceManager.AddNamespace("ssac", "http://extn.ssac.ee.sim.dsh.cms.hhs.gov");
var ssnIds = doc.XPathSelectElements("soap:Envelope/soap:Body/exch:SSACompositeResponse/ssac:SSACompositeIndividualResponse/ssac:PersonSSNIdentification", namespaceManager);
foreach (var ssnId in ssnIds)
if (ssnId.Value == "199123051")
ssnId.Value = "9876543210";
}
Be sure to do using System.Xml.XPath; at the beginning of the file since XPathSelectElements is an extension method.
Update
Using XmlDocument, the equivalent XPATH query is:
var xmlDoc = new XmlDocument();
xmlDoc.Load(newSSAPathName);
var nameTable = xmlDoc.NameTable;
var namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
namespaceManager.AddNamespace("exch", "http://ssac.ee.sim.dsh.cms.hhs.gov");
namespaceManager.AddNamespace("ssac", "http://extn.ssac.ee.sim.dsh.cms.hhs.gov");
var ssnIds = xmlDoc.SelectNodes("soap:Envelope/soap:Body/exch:SSACompositeResponse/ssac:SSACompositeIndividualResponse/ssac:PersonSSNIdentification", namespaceManager);
foreach (XmlNode ssnId in ssnIds)
if (ssnId.InnerText == "199123051")
ssnId.InnerText = "9876543210";

Navigate xml nodes;

Hi I have an xml data returned from another service. It looks like this
<?xml version="1.0" encoding="UTF-8"?>
<response xmlns="http://test.com/group/application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Response>
<Response>
<ReturnCode>0</ReturnCode>
<Message>Sucess</Message>
<Data>PRINT 'This is a test #2'</Data>
</Response>
</Response>
</response>
I need the value of Data, Message and ReturnCode. The value inside the Data(PRINT 'This is a test #2') node could be single line or thousands of lines..
I am using this C# code to get the values
XmlDocument xm = new XmlDocument();
string Response = obj.getContent(str, 1, 73810, SHA);
//Console.WriteLine("Response" + Response);
xm.LoadXml(Response);
Console.WriteLine(xm.InnerXml);
XmlNode oldCd;
XmlElement root = xm.DocumentElement;
Console.WriteLine(root.InnerText);
oldCd = root.SelectSingleNode("/response/Response/Response/ReturnCode/Message/Data/");
static void Main()
{
try
{
svc obj = new svc();
..
//XmlDocument xm = new XmlDocument();
string rsp = obj.getContent(..;
String myEncodedString;
myEncodedString = obj.XmlDecode(rsp);
XNamespace xmlns = XNamespace.Get("http://xxxx.com/xxx/xx");
XDocument doc = XDocument.Parse(myEncodedString);
Console.WriteLine(obj.Return_Message_Data("ReturnCode", myEncodedString));
Console.WriteLine(obj.Return_Message_Data("Message", myEncodedString));
Console.WriteLine(obj.Return_Message_Data("Data", myEncodedString));
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
Try this
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); //myXmlString is the xml file in string //copying xml to string: string myXmlString = xmldoc.OuterXml.ToString();
XmlNodeList xnList = xml.SelectNodes("/responset[#*]/Response");
foreach (XmlNode xn in xnList)
{
XmlNode response = xn.SelectSingleNode("Response");
if (response != null)
{
string rc = response["ReturnCode"].InnerText;
string msg = example["Message"].InnerText;
string data = example["Data"].InnerText;
}
}

How to get all different element tags from root tag using XPath

I have a following xml file
<root>
<element1>
<header>header1</header>
<tag1>tag1</tag1>
<response>
<status>success</status>
<Data>
<id>d1</id>
<test>2</test>
</Data>
<Beta>
<betaid>sdsd</betaid>
<code>123</code>
<code>ddd</code>
</Beta>
</response>
</element1>
</root>
My Question: How to get the first child elements under "Response" tag? i.e staus, data and beta.
Using XPath in C#. Thank you
The .net code i have is here but it does not work.
XPathDocument doc= new XPathDocument(XmlReaderdata);
XPathNavigator mes, Nav = doc.CreateNavigator();
foreach(XPathNavigator node in (XPathNodeIterator)Nav.Evaluate("//response/*)
{
node.Name;
}
An XPath query like this should work:
//response/*
For example:
var xml = #"<root> ... </root>";
using (StringReader stream = new StringReader(xml))
{
XPathDocument doc= new XPathDocument(stream);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator itor = (XPathNodeIterator)nav.Evaluate("//response/*");
foreach(XPathNavigator node in itor)
{
Console.WriteLine(node.Name);
}
}
Produces the output:
status
Data
Beta
You can use //response:
DTO:
public class Response
{
public Response()
{
Data = new List<KeyValuePair<string, string>>();
Beta = new List<KeyValuePair<string, string>>();
}
public string Status { get; set; }
public List<KeyValuePair<string, string>> Data { get; set; }
public List<KeyValuePair<string, string>> Beta { get; set; }
}
Code:
var document = XDocument.Parse(data);
var element = document.XPathSelectElement("//response");
var response = new Response();
response.Status = element.Element("status").Value;
foreach(var dataElement in element.Element("Data").Elements())
{
response.Data.Add(new KeyValuePair<string, string>(dataElement.Name.LocalName, dataElement.Value));
}
foreach(var betaElement in element.Element("Beta").Elements())
{
response.Beta.Add(new KeyValuePair<string, string>(betaElement.Name.LocalName, betaElement.Value));
}
Edit: Partial loading
public Response ParseResponse(XPathDocument document)
{
var navigator = document.CreateNavigator();
var iterator = navigator.Select("//response");
iterator.MoveNext();
var responseDoc = XDocument.Parse(iterator.Current.OuterXml);
var element = responseDoc.Element("response");
var response = new Response();
response.Status = element.Element("status").Value;
foreach(var dataElement in element.Element("Data").Elements())
{
response.Data.Add(new KeyValuePair<string, string>(dataElement.Name.LocalName, dataElement.Value));
}
foreach(var betaElement in element.Element("Beta").Elements())
{
response.Beta.Add(new KeyValuePair<string, string>(betaElement.Name.LocalName, betaElement.Value));
}
return response;
}
Response response;
using(var reader = XmlReader.Create(stream))
{
var doc = new XPathDocument(reader);
response = ParseResponse(doc);
}
Are you trying to get the names of the child nodes?
i hope this will help
string xmlstring = "<root><element><response><status>Success</status><Data><id>1</id></Data></response></element></root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);
XmlNode node = doc.SelectSingleNode("/root/element/response");
XmlNodeList children = node.ChildNodes;
foreach(XmlNode i in children )
Console.WriteLine(i.Name);

Categories

Resources