2009-07-08 60 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