[英]Can I get a distinct list of XML TagName using C#?
I have a very long xml file and I need to identify what are the distinct TagName in that xml file. 我有一个非常长的xml文件,我需要确定该xml文件中不同的TagName。 I wonder if I can get it in my C# application with XmlDocument library.
我想知道是否可以使用XmlDocument库在C#应用程序中获取它。
In this example xml, I want to find all the TagName: bookstore, book genre, title, first name 在此示例xml中,我想查找所有TagName:书店,书体裁,书名,名字
<bookstore>
<book genre="novel">
<title>The Autobiography of Benjamin Franklin</title>
</book>
<book genre="novel">
<title>The Confidence Man</title>
<first-name>Herman</first-name>
</book>
</bookstore>
Parse it as an XDocument
and you could do this: 将其解析为
XDocument
,您可以执行以下操作:
var names = doc.Descendants().Select(e => e.Name.LocalName).Distinct();
This will give you the results (in some order): 这将为您提供结果(按一定顺序):
bookstore
book
title
first-name
Otherwise if you must use an XmlDocument
, you could do this: 否则,如果必须使用
XmlDocument
,则可以执行以下操作:
var names = doc.DocumentElement
.SelectNodes("//*").Cast<XmlNode>()
.Select(e => e.LocalName)
.Distinct();
You can use HashSet
to get distinct names. 您可以使用
HashSet
获得不同的名称。 Moreover, it is very fast. 而且,它非常快。
var doc = XDocument.Load("test.xml");
var set = new HashSet<string>();
foreach (var node in doc.Descendants())
{
set.Add(node.Name.LocalName);
foreach (var attr in node.Attributes())
set.Add(attr.Name.LocalName);
}
foreach (var name in set)
Console.WriteLine(name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.