有人可以帮助以下地方(我正在努力形成查询)
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>
类
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; }
}
我的解决方案:
public void example3()
{
var xElem = XElement.Load("test.xml");
var myobject = xElem.Descendants("response").Select(
x => new MarketClockResponse
{
//Struggling to proceed from here
});
}
答案 0 :(得分:2)
您正在尝试从response
元素(xml的根目录)中选择response
个元素。直接使用此元素:
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")
}
}
};
答案 1 :(得分:1)
var myobject = xElem.Descendants("response").Select(
x => new MarketClockResponse
{
response = new Response
{
Id = x.Attribute("id").Value,
//.....
//populate all the attributes
}
});
答案 2 :(得分:1)
首先,我会使用XDocument.Load
而不是XElement.Load
,因为您的XML是一个文档,带有声明等。
var xDoc = XDocument.Load("Input.txt");
然后,我设置了两个局部变量,以避免多次查询同一个事件:
var resp = xDoc.Root;
var status = resp.Element("status");
使用它们来获得你需要的东西:
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")
}
}
};