LINQ to XML语法

Ste*_*ard 2 c# linq linq-to-xml

我有一个简单的POCO类来保存从XML文件中提取的数据,定义如下:

public class Demographics
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string Gender { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个相当简单的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>
Run Code Online (Sandbox Code Playgroud)

我遇到的挑战是将中间的初始名称和/或名字输入到我班级的正确属性中.如您所见,名称节点内有两个给定节点,中间首字母由"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();
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 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()
Run Code Online (Sandbox Code Playgroud)

编辑:查询语法在这里有点尴尬.对于第一个版本,它将是:

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

我个人坚持使用点符号.