【问题标题】:LINQ to XML SyntaxLINQ to XML 语法
【发布时间】:2009-07-08 23:30:25
【问题描述】:

我有一个简单的 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; }
}

我有一个相当简单的 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>

我面临的挑战是将中间名首字母和/或名字放入班级中的正确属性中。如您所见,name 节点内有两个 given 节点,中间的首字母由“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();
}

【问题讨论】:

    标签: c# linq linq-to-xml


    【解决方案1】:

    怎么样:

    // 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()
    

    我个人会坚持使用点符号。

    【讨论】:

    • 好的,我认为这似乎有点明显。我有点沉迷于使用查询语法,这可能是我的失败。如果你有时间,你介意用那种语法回答一下吗?我也想看看我哪里出错了。一如既往,非常感谢乔恩。
    • 再次感谢。我看到你关于查询语法的观点很尴尬。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2015-05-27
    相关资源
    最近更新 更多