![](/img/trans.png)
[英]How to get all texts in C# from child nodes but avoid a text from those child that has specific attribute (such as removed)
[英]how to get specific nodes which has specific attribute in c#
我想找到具有特定属性的节点(例如在下面的示例中,我们具有属性attr)
<root>
<anynode id="1" attr="abc">
first node
</anynode>
<anynode id="2">
2nd node
</anynode>
<anynode id="3" attr="abc">
3rd node
</anynode>
<anynode id="4" attr="def">
4th node
</anynode>
</root>
我想让它同时遍历XMLDocument和XDocument,如果我可以一次迭代获得ID和ATTR的值,那将是很棒的,我在Google上做了一些搜索,但是我没有找到任何可以帮助我达到最终结果的方法
1,abc , first node
3,abc , 3rd node
4,def , 4th node
任何帮助将不胜感激
使用System.Xml.Linq命名空间,我们可以利用XDocument类查找“ anynode”元素的“ id”和“ attr”属性。
var xmlDocument = XDocument.Load(@"path to xml file");
var nodes = xmlDocument.Element("root")?.Elements("anynode");
if (nodes == null)
return;
foreach (var node in nodes)
{
var id = node.Attribute("id")?.Value;
var attr = node.Attribute("attr")?.Value;
Console.WriteLine($"ID = {id}, ATTR = {attr}");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.