这是我的 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/