如何获取不同节点中特定属性的值?
How to get the values of a specific attribute in different nodes?
我有一个 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>
</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
的所有值(自关闭节点除外),即输出应该是 list/array值 abc1、xyz1、10。
如何使用 LINQ-TO-XML?
执行此操作
是否有与属性的 Descendants
方法等效的方法?
您需要从具有属性 add
且不是包含 add
属性的自闭节点的后代中筛选。
类似于:
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);
}
您需要包括 usings
这两个:
using System.Xml.Linq;
using System.Linq;
输出:
abc1
xyz1
10
更新:
根据您关于在关闭标记单独但为空(即其中没有值)的情况下排除它的查询:
where note.Attribute("add") !=null && (!note.IsEmpty || !String.IsNullOrEmpty(note.Value))
我有一个 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>
</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
的所有值(自关闭节点除外),即输出应该是 list/array值 abc1、xyz1、10。
如何使用 LINQ-TO-XML?
是否有与属性的 Descendants
方法等效的方法?
您需要从具有属性 add
且不是包含 add
属性的自闭节点的后代中筛选。
类似于:
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);
}
您需要包括 usings
这两个:
using System.Xml.Linq;
using System.Linq;
输出:
abc1
xyz1
10
更新:
根据您关于在关闭标记单独但为空(即其中没有值)的情况下排除它的查询:
where note.Attribute("add") !=null && (!note.IsEmpty || !String.IsNullOrEmpty(note.Value))