Reputation: 175
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".
Upvotes: 0
Views: 369
Reputation: 28809
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"));
Upvotes: 4
Reputation: 119
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;
Upvotes: 0