【问题标题】:linq-xml Query not returning expected resultslinq-xml 查询未返回预期结果
【发布时间】:2014-03-24 21:34:54
【问题描述】:

我有以下由html标签组成的xml文件,如下所示:

<?xml version="1.0" encoding="UTF-8"?>

<html>
<head>
<title>
title1
</title>
</head>

<body>
<fragment id="heading1">
<h1>
Heading 1
</h1>
</fragment>
<fragment id="heading2">
<h2>
Heading 2
</h2>
</fragment>
<fragment id="paragraph1">
<p>
Paragraph 1
</p>
</fragment>
</body>                  
</html>

我正在尝试提取所有片段 ID 并使用 linq-xml 显示它们。查询如下图:

XDocument xelement = XDocument.Load("Path\\To\\XMLFile"); 
var name = from nm in xelement.Descendants("body")
select nm.Element("fragment").Attribute("id").Value;
Console.WriteLine(name);

这个查询返回的输出是:

标题1

但我想要的是:

标题1 标题2 第1段

我做错了什么? 请多多指教。

谢谢

【问题讨论】:

    标签: linq linq-to-xml linqpad


    【解决方案1】:

    您可以使用选择值

    IEnumerable<string> names = from id in xelement.Descendants("fragment").Attributes("id") select id.Value;
    

    IEnumerable<string> names = from frag in xelement.Descendants("fragment") select frag.Attribute("id").Value;
    

    【讨论】:

      【解决方案2】:

      我已经测试过了,它工作正常!!

      XDocument po = XDocument.Load(@"XMLFile1.xml");
            IEnumerable<string> names = from id in po.Descendants("fragment").Attributes("id") select id.Value;
                  string str = string.Empty;
                  foreach (var el in names)
                  {
                      str += el;               
                  }
                  System.Console.WriteLine(str);
                  Console.ReadKey();
      

      【讨论】:

      • 谢谢尼尔。但是你能解释一下为什么它不适用于 XDocument 吗?
      • 它适用于 XDocument,请参阅我的更新答案@Anvith
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多