2009-07-08 64 views
2

我有一個簡單的POCO類來保存自定義爲一個XML文件中提取數據如下:的LINQ to XML語法

public class Demographics 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string MiddleName { get; set; } 
    public string Gender { get; set; } 
} 

我已經有了一個相當直接的XML文件(或相當元素這種情況下)來提取數據,定義如下:

<patient determinerCode="INSTANCE"> 
    <name use="L"> 
     <given>John</given> 
     <given qualifier="IN">Q.</given> 
     <family>Public</family> 
    </name> 
    <administrativeGenderCode code="F" displayName="Female"/> 
</patient> 

時遇到的挑戰是讓中間的初始和/或名字到我班上正確的屬性。正如你所看到的,有兩個給出節點內部節點和中間最初是由「IN」屬性指定。有沒有簡單的LINQ語法,我在這裏丟失,或者我需要查詢所有給定的節點,並通過它們枚舉來正確放置每個節點?

我的代碼,因爲它目前爲,看起來是這樣的:

private string GetInterfaceXmlData(XElement source) 
{ 
     //Source in this context represents the "patient" element as you see in the example. 
     //The NMSPC constant represents the namespace for this XML document which is not specifically displayed 
     //in the XML example. 
     Demographics currentDemo = new Demographics() 
     { 
      //I realize that this particular reference to FirstName is not optimal, as it may not actually 
      //be the first "given" node under the name node, it's simply a place holder for now. 
      FirstName = source.Element(NMSPC + "name").Element(NMSPC + "given").Value, 
      LastName = source.Element(NMSPC + "name").Element(NMSPC + "family").Value, 
      Gender=source.Element(NMSPC+"administrativeGenderCode").Attribute("code").Value, 
     }; 
     XElement result = new XElement("XML"); 
     result.Add(new XElement("Demographics")); 
     return result.ToString(); 
} 

回答

6

關於如何:

// For the first name 
source.Element(NMSPC + "name") 
     .Elements(NMSPC + "given") 
     .Where(element => element.Attribute("IN") == null) 
     .First() 

// For the initial 
source.Element(NMSPC + "name") 
     .Elements(NMSPC + "given") 
     .Where(element => element.Attribute("IN") != null) 
     .First() 

編輯:查詢語法是這裏有點尷尬。對於第一個版本,它將是:

(from element in .Element(NMSPC + "name").Elements(NMSPC + "given") 
where element.Attribute("IN") == null 
select element).First() 

我個人堅持使用點符號表示這一點。

+0

好吧,正如我所見,這似乎有點顯而易見。我有點使用查詢語法,這可能是我的失敗。如果你有時間,你會介意以這種語法來回應一個響應嗎?我想看看我在哪裏出錯。一如既往,非常感謝喬恩。 – 2009-07-08 15:16:22