c# - IEnumerable<XAttribute> 返回 Null,需要返回属性值

标签 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,并且需要返回属性名称“Nid”的属性。

 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();
                    }
                }

最佳答案

这可能对您有所帮助。您编写的所有代码都是正确的,您只是更愿意使用 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;

关于c# - IEnumerable<XAttribute> 返回 Null,需要返回属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17908963/

相关文章:

c# - 使用无效键值 : "fields". 访问的 JArray 值应为数组位置索引

c# - Luca Bolognese 的 "LINQ to SQL Overview"视频在哪里?

c# - C#任务-从UI异步获取值(value)

c# - 具有精确表达式的起订量<Func<TEntity, bool>>

c# - 在 EF 查询中添加 DateTime 和 TimeSpan 的代码示例

c# - C#在线程间安全使用LINQ

c# - LINQ 以通用和递归的方式查询 DTO 以获取特定的名称-值对

c# - 在 asp.net mvc 4 中获取登录用户的 ID

c# - 如何将新行放入 wpf TextBlock 控件中?

c# - 使用值初始化 C# 字典的正确方法