C# 如何获取不同节点中特定属性的值?
我有一个xml文件,看起来像C# 如何获取不同节点中特定属性的值?,c#,linq-to-xml,C#,Linq To Xml,我有一个xml文件,看起来像 <?xml version="1.0"?> <notes> <note> <to>Tove</to> <from add="abc1">Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> &
<?xml version="1.0"?>
<notes>
<note>
<to>Tove</to>
<from add="abc1">Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<to add="xyz1">Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this <rref add="10">10</rref> weekend!</body>
<pol add="adt10"/>
</note>
</notes>
托弗
贾尼
提醒
这个周末别忘了我!
托弗
贾尼
提醒
这个周末别忘了我!
我想从具有该属性的所有不同节点获取属性add
(自关闭节点除外)的所有值,即输出应该是值abc1、xyz1、10的列表/数组。
如何使用LINQ-TO-XML实现这一点
对于属性,是否存在与
子体
方法等效的方法?您需要从具有属性添加
且不是包含添加
属性的自动关闭节点的子体中进行筛选
比如:
var nodess = from note in Doc.Descendants()
where note.Attribute("add") !=null && !note.IsEmpty
select note.Attribute("add").Value;
foreach(var node in nodess)
{
Console.WriteLine(node);
}
您需要包括以下两种用法中的用法:
using System.Xml.Linq;
using System.Linq;
输出:
abc1
xyz1
十,
看
更新:
根据您的查询,如果关闭标记单独但为空,即其中没有值,则将其排除:
where note.Attribute("add") !=null && (!note.IsEmpty || !String.IsNullOrEmpty(note.Value))
那
呢?您想将其与
区分开来吗?如果没有“除了自关闭节点”部分,这是微不足道的。。。只需使用doc.subjects()。选择(x=>x.Attribute(“adt”))。其中(attr=>attr!=null)。选择(attr=>attr.Value)。ToArray()
。从这里开始,您只需要在查询的早期过滤掉自动关闭元素。不,我不想区分
和
…但即使我想区分,那又怎么样?抱歉,伙计们,这是我的复制粘贴错误,因为复制自我现有的演示小提琴,更正它。如果我不想从空节点(不是自动关闭格式)获取属性值add
,如
添加另一个条件,如:&&,该怎么办!String.IsNullOrEmpty(note.Value)
在where
@Bumba中,很抱歉这将是where note.Attribute(“添加”)=null&(!note.IsEmpty | |!String.IsNullOrEmpty(note.Value))