2

有人可以在以下地方提供帮助(我正在努力形成查询)

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  
        });
} 
4

3 回答 3

2

您正在尝试responseresponse元素(这是您的 xml 的根目录)中选择元素。直接使用此元素:

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")
        }
    }
};
于 2013-10-02T14:54:50.050 回答
1
var myobject = xElem.Descendants("response").Select(
        x => new MarketClockResponse
        {
              response = new Response
             {
                Id = x.Attribute("id").Value,
                //.....
                //populate all the attributes
             }
        });
于 2013-10-02T14:56:47.163 回答
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")
        }
    }
};
于 2013-10-02T14:58:47.807 回答