Reputation: 8636
I have the following xml which is returning from an api:
<?xml version="1.0" encoding="utf-8"?>
<response>
<error>
<errorcode>1002</errorcode>
<errortext>there is already an open session</errortext>
</error>
</response>
I would like to read the error code. I write up the following code:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(result1);
XmlNode node = xmlDoc.DocumentElement.SelectSingleNode("/response").ChildNodes[0].ChildNodes[0].InnerText
Is there any other way of doing this by using linq or some other technique?
I am using an api to call as follows
HttpClientHandler handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler);
var result = client.GetAsync(new Uri("https://api/access.mth?username=xyz&password=xyz@2021)).GetAwaiter().GetResult();
StreamReader reader = new StreamReader(result.Content.ReadAsStringAsync().Result);
Upvotes: 0
Views: 2809
Reputation: 8743
You can use the XML serializer which is located in the namespace System.Xml.Serialization. Create a class with a paramterless constructor that has public properties with getters and setters according to your XML elements:
public class response
{
public error error {get;set;}
}
public class error
{
public int errorcode {get;set;}
public string errortext {get;set;}
}
Note: the parameterless constructor is created here implicitly by the compiler, because no constructor is defined at all.
You can load the file via
using StreamReader reader = new StreamReader("file.xml");
XmlSerializer serializer = new XmlSerializer(typeof(response));
var result = (response)serializer.Deserialize(reader);
int errorCode = result.error.errorcode;
You have some flexibility regarding the format of the XML file. For example if you have also this file to parse:
<response>
<returncode>
<code>100</code>
<description>successful</description>
</returncode> <authkey>xxxx<authkey>
</response>
You can modify your class structure:
public class response
{
public error error {get;set;}
public returncode returncode {get;set;}
public string authkey {get;set;}
}
public class error
{
public int errorcode {get;set;}
public string errortext {get;set;}
}
public class returncode
{
public int code {get;set;}
public string description {get;set;}
}
If you parse a file of first format, returncode
and authkey
will be null. If you parse a file of second format, error
will be null.
Upvotes: 3