【问题标题】:How to retrieve the name of the attribute dynamically without specifying the name of the attribute ?如何在不指定属性名称的情况下动态检索属性名称?
【发布时间】:2010-08-13 14:09:01
【问题描述】:

我正在开发 asp.net 移动应用程序。我正在使用 LINQ to XML 来查询 XML 文件。我正在使用以下查询来动态检索查询的名称和值,如下所示

var TotalManifolds = from MF in FieldRoot.Element("FIELD-DEFINITION").Element("MANIFOLDS").Elements("MANIFOLD")
                     join SLT in FieldRoot.Element("FIELD-DEFINITION").Element("SLOTS").Elements("SLOT")
                     on (string)MF.Attribute("MID") equals (string)SLT.Attribute("PARENT")
                     select new
                     {
                         SlotName = (string)SLT.Attribute("NAME").Value,
                         SlotValue = (string)SLT.Attribute("NAME").Value
                     };

在上述查询的以下语句中,我想在不明确指定属性名称的情况下动态检索属性名称

 SlotName = (string)SLT.Attribute("NAME").Value

这里我明确指定了名称。我想编写可以动态检索属性名称的代码。我是 Linq to xml 的新手。你能告诉这如何以编程方式完成吗?或者你能提供我可以解决上述问题的链接吗?

【问题讨论】:

    标签: c# asp.net join attributes linq-to-xml


    【解决方案1】:

    您似乎正在寻找类似的东西:

    // ...
    select new
    {
        SlotName = SLT.Attributes().First().Name,
        SlotValue = SLT.Attributes().First().Value
    };
    

    【讨论】:

      【解决方案2】:

      如果我理解正确,您可以随时将变量传递给 LINQ 查询:

      var string attrName = "NAME";  // specify whatever value you need ...
      
      // wrap the query below in a function, if it will be reused...
      var TotalManifolds = from MF in FieldRoot.Element("FIELD-DEFINITION").Element("MANIFOLDS").Elements("MANIFOLD")  
                       join SLT in FieldRoot.Element("FIELD-DEFINITION").Element("SLOTS").Elements("SLOT")  
                       on (string)MF.Attribute("MID") equals (string)SLT.Attribute("PARENT")  
                       select new  
                       {  
                           SlotName = (string)SLT.Attribute(attrName).Value,  
                           SlotValue = (string)SLT.Attribute(attrName).Value  
                       }; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-29
        • 1970-01-01
        • 2012-08-21
        • 1970-01-01
        • 2013-05-10
        • 1970-01-01
        • 2013-03-31
        相关资源
        最近更新 更多