Reputation: 884
Can somebody please help with the below place (where I am struggling to form the query)
XML
<?xml version="1.0" encoding="UTF-8"?>
<response id="1545346343">
<date>2013-10-01 12:01:55.532999</date>
<status>
<current>open</current>
<change_at>16:00:00</change_at>
</status>
<message>Market is open</message>
</response>
Class
public class MarketClockResponse
{
public Response response { get; set; }
}
public class Response
{
public string Id { get; set; }
public string date { get; set; }
public Status status { get; set; }
public string message { get; set; }
}
public class Status
{
public string current { get; set; }
public string change_at { get; set; }
}
My solution:
public void example3()
{
var xElem = XElement.Load("test.xml");
var myobject = xElem.Descendants("response").Select(
x => new MarketClockResponse
{
//Struggling to proceed from here
});
}
Upvotes: 2
Views: 109
Reputation: 125630
First of all, I would use XDocument.Load
instead of XElement.Load
, because your XML is a document, with declaration, etc.
var xDoc = XDocument.Load("Input.txt");
Then, I'd set two local variables to avoid querying for the same thing more than once:
var resp = xDoc.Root;
var status = resp.Element("status");
And use them to get what you need:
var myobject = new MarketClockResponse
{
response = new Response
{
Id = (string)resp.Attribute("id"),
date = (string)resp.Element("date"),
message = (string)resp.Element("message"),
status = new Status
{
current = (string)status.Element("current"),
change_at = (string)status.Element("change_at")
}
}
};
Upvotes: 1
Reputation: 14915
var myobject = xElem.Descendants("response").Select(
x => new MarketClockResponse
{
response = new Response
{
Id = x.Attribute("id").Value,
//.....
//populate all the attributes
}
});
Upvotes: 1
Reputation: 236228
You are trying to select response
elements from response
element (which is root of your xml). Use this element directly instead:
var responseElement = XElement.Load(path_to_xml);
var statusElement = responseElement.Element("status");
var myobject = new MarketClockResponse
{
response = new Response
{
Id = (string)responseElement.Attribute("id"),
date = (string)responseElement.Element("date"),
message = (string)responseElement.Element("message"),
status = new Status
{
current = (string)statusElement.Element("current"),
change_at = (string)statusElement.Element("change_at")
}
}
};
Upvotes: 2