c# - 单独获取XML中的标签值

标签 c# linq linq-to-xml

这是我的 XML 文件:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<categories>
    <category1 name="Music">
        <file>tabla.txt</file>
        <file>sitar.txt</file>
    </category1>

    <category2 name="Documents">
        <file>OCD1.txt</file>
        <file>OCD2.txt</file>
    </category2>

    <category3 name="Movies">
            <file>Thisistheend.txt</file>
        <file>TheInternship.txt</file>
    </category3>
</categories>

我使用以下查询来获取标签值:

q = from x in doc.Descendants() where (x.Attributes().Count()>0
&& (x.Attribute("name").Value == key) select x; 

但是<File>标签值被附加。当我尝试显示每个值时,例如: <file> “文档”的标记值在 ListView 框中显示为“OCD1.txtOcd2.txt”。如何在 LINQ 查询中分离这两个值?

最佳答案

您可以使用 SelectMany 查询获取文件内容。在查询语法中,您可以通过在匹配类别上添加额外的 from/select 查询来实现此目的。

var query = from x in doc.Descendants()
            where (string)x.Attribute("name") == key
            from file in x.Elements("file")
            select file.Value;

另请注意,我更新了过滤以直接检查 name 属性。您可以避免检查属性计数。这是不必要的,并且不能保证 name 属性的存在。如果您试图防止缺少 name 属性,那么您可以强制转换该属性,如果该属性不存在,则会返回 null。我已经使用这段代码完成了此操作:(string)x.Attribute("name") == key

关于c# - 单独获取XML中的标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19872366/

相关文章:

c# - 计算 2 个列表中存在的项目

.net - 使用 linq 按列索引对 vb.net 中的数据表进行排序

c# - GIT 智能 HTTP 协议(protocol)的服务端和客户端有哪些细节区别

c# - WCF REST - 是否可以在不结束执行的情况下返回响应?

c# linq-to-sql EF 查询以匹配特定的 JSON 结构

c# - 如果我从 XDocument 创建 XElements 列表,是否会在内存中创建元素列表的新副本?

c# - linq 问题 : querying nested collections

xml - 如何将 StreamReader 转换为 XDocument?

c# - 与 string.Empty (c#) 相比的最佳性能

c# - 从城市 0 到 N 的最短路径(公路/航空混合成本)