0

For the following string xml value, I need to fetch the value of node "ReturnStr"

<ArrayOfAppExportReturnStruct
 xmlns=\"http://schemas.datacontract.org/2004/07/ClientWebService\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n 
 <AppExportReturnStruct>\r\n    
 <Key1>0</Key1>\r\n    <Key2>0</Key2>\r\n  
 <PeriodDT>2019-02-26T00:00:00</PeriodDT>\r\n   
 <ReturnCode>1</ReturnCode>\r\n    
 <ReturnStr>Failure - No Deal found based on input parameters passed.</ReturnStr>\r\n  
 </AppExportReturnStruct>\r\n
</ArrayOfAppExportReturnStruct>

I used the following code

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString.Replace("\r\n",""));
string alarmDesc;

string xpath = "ArrayOfAppExportReturnStruct/AppExportReturnStruct";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
    alarmDesc = childrenNode.SelectSingleNode("ReturnStr").InnerText;
}

I am getting nothing in nodes var. What is the right way to get ReturnStr's node value in "alarmDesc".

2 Answers 2

4

The XML text most probably does not actually include \r\n or any other escape characters, that's just how Visual Studio chooses to represent the string when you're debugging. Parsing XML does not depend on whitespace either, so replacing these strings in the value is almost certainly not necessary. To select the node, you need to include the namespace. I suggest you use XElement rather than XmlDocument, because it's got a much friendlier interface:

var xml = XElement.Parse(xmlDocument);
XNamespace ns = "http://schemas.datacontract.org/2004/07/ClientWebService";
var alarmDesc = (string) xml.Element(ns + "AppExportReturnStruct").Element(ns + "ReturnStr");

With more than element, use .Elements rather than .Element, in a foreach loop. You can even use LINQ for that if you're just interested in particular bits:

var alarmDescriptions = xml
    .Elements(ns + "AppExportReturnStruct")
    .Select(e => (string) e.Element(ns + "ReturnStr"));
Sign up to request clarification or add additional context in comments.

Comments

0

You can simply do this if there is only one loop.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString.Replace("\r\n",""));
string alarmDesc = xmlDoc.GetElementsByTagName("ReturnStr").Item(0).InnerText;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.