IEnumerable <xattribute>返回Null,需要返回属性值</xattribute>

时间:2013-07-28 13:59:43

标签: c# linq

这是一个示例xml我只需要Nid属性

<Server>
  <Network Nid="43d5377-0dcd-40e6-b95c-8ee980b1e248">
  <Client_Group id="20">963440d0-96dc-46a4-a54d-7251a65f585f</Client_Group>
  <ClientID id="20">3fc8ffa1-c16b-4d7b-9e55-1e88dfe15277</ClientID>
<Server>

这是XAttributes的IEnumerable,因此我们可以使用Linq查询XML文档中的属性,使用XElement访问XML文件。由于某种原因,这将返回Null,它需要返回属性名称的属性&#34; Nid&#34;。

 XElement main = XElement.Load(fi.FullName);

IEnumerable<XAttribute> successAttributes =
                 from attribute in main.Attributes()
                 where attribute.Name.LocalName == "Nid"
                 select attribute;

这是我执行Linq查询以将属性放在数组

中的位置
foreach (string attribute in successAttributes)
                { 
                    for (int i = 0; i < IntializedPorts.Count(); i++)
                    {
                      //running Intialization
                      IntializedNetworks[i] = attribute.ToString();
                    }
                }

2 个答案:

答案 0 :(得分:0)

main这里是根元素:<Server> - 它没有Nid属性。

你想要这样的东西:

Guid nid = (Guid)main.Element("Network").Attribute("Nid");

或多人:

Guid[] arr = (from attr in main.DescendentsOrSelf().Attributes("Nid")
              select (Guid)attr).ToArray();

答案 1 :(得分:0)

这可能会对你有所帮助。您编写代码的所有内容都是正确的,您只需使用main.Element("Network").Attributes()而不是main.Attributes()

IEnumerable<XAttribute> successAttributes =
                 from attribute in main.Element("Network").Attributes()
                 where attribute.Name.LocalName == "Nid"
                 select attribute;

代表这个问题,我编写了下面的示例程序,它将产生预期的NID值

string strVal = "<Server><Network Nid=\"43d5377-0dcd-40e6-b95c-8ee980b1e248\"/><Client_Group id=\"20\">963440d0-96dc-46a4-a54d-7251a65f585f</Client_Group><ClientID id=\"20\">3fc8ffa1-c16b-4d7b-9e55-1e88dfe15277</ClientID></Server>";

            XElement main = XElement.Load(new StringReader(strVal));

            IEnumerable<XAttribute> successAttributes =
                 from attribute in main.Element("Network").Attributes()
                 where attribute.Name.LocalName == "Nid"
                 select attribute;