2013-10-02 68 views
2

有人可以請與下面的地方幫助(其中我很努力形成查詢)的LINQ to XML轉換器

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

XML是否始終只包含一個'response'元素? – MarcinJuraszek

+0

什麼查詢?問題是什麼。 – Liam

+0

他不知道如何從xelement構建對象 – Jonesopolis

回答

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

謝謝澄清我的概念 – Patrick

1
var myobject = xElem.Descendants("response").Select(
     x => new MarketClockResponse 
     { 
       response = new Response 
      { 
       Id = x.Attribute("id").Value, 
       //..... 
       //populate all the attributes 
      } 
     }); 
1

首先,我會用XDocument.Load代替XElement.Load,因爲你的XML是一個文檔,以聲明等。

var xDoc = XDocument.Load("Input.txt"); 

然後,我'd設置兩個局部變量以避免多次查詢同一件事:

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") 
     } 
    } 
}; 
+0

謝謝您一步一步地指導XDoc和XElement – Patrick