C# 如何从 xml 文件中获取所有元素名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/847978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# how can I get all elements name from a xml file
提问by Smallville
I'd like to get all the element name from a xml file, for example the xml file is,
我想从 xml 文件中获取所有元素名称,例如 xml 文件是,
<BookStore>
<BookStoreInfo>
<Address />
<Tel />
<Fax />
<BookStoreInfo>
<Book>
<BookName />
<ISBN />
<PublishDate />
</Book>
<Book>
....
</Book>
</BookStore>
I would like to get the element's name of "BookName". "ISBN" and "PublishDate " and only those names, not include " BookStoreInfo" and its child node's name
我想获得“BookName”的元素名称。"ISBN" 和 "PublishDate " 以及仅这些名称,不包括 "BookStoreInfo" 及其子节点的名称
I tried several ways, but doesn't work, how can I do it?
我尝试了几种方法,但都不起作用,我该怎么办?
采纳答案by Marc Gravell
Well, with XDocumentand LINQ-to-XML:
好吧,使用XDocumentLINQ-to-XML:
foreach(var name in doc.Root.DescendantNodes().OfType<XElement>()
.Select(x => x.Name).Distinct())
{
Console.WriteLine(name);
}
There are lots of similar routes, though.
有很多类似的路线,虽然。
回答by Fredrik Leijon
Using XPath
使用 XPath
XmlDocument xdoc = new XmlDocument();
xdoc.Load(something);
XmlNodeList list = xdoc.SelectNodes("//BookStore");
gives you a list with all nodes in the document named BookStore
为您提供一个列表,其中包含名为 BookStore 的文档中的所有节点
回答by Kirtan
You can try doing it using XPATH.
您可以尝试使用XPATH 进行操作。
XmlDocument doc = new XmlDocument();
doc.LoadXml("xml string");
XmlNodeList list = doc.SelectNodes("//BookStore/Book");
回答by Winston Smith
If you're using C# 3.0, you can do the following:
如果您使用的是 C# 3.0,则可以执行以下操作:
var data = XElement.Load("c:/test.xml"); // change this to reflect location of your xml file
var allElementNames =
(from e in in data.Descendants()
select e.Name).Distinct();
回答by Adam Robinson
The purists way of doing this (and, to be fair, the right way) would be to have a schema contract definition and read it in that way. That being said, you could do something like this...
这样做的纯粹主义者的方式(公平地说,正确的方式)是拥有一个模式契约定义并以这种方式阅读它。话虽如此,你可以做这样的事情......
List<string> nodeNames = new List<string>();
foreach(System.Xml.XmlNode node in doc.SelectNodes("BookStore/Book"))
{
foreach(System.Xml.XmlNode child in node.Children)
{
if(!nodeNames.Contains(child.Name)) nodeNames.Add(child.Name);
}
}
This is, admittedly, a rudimentary method for obtaining the list of distinct node names for the Booknode's children, but you didn't specify much else in the way of your environment (if you have 3.5, you could use LINQ to XML to make this a little prettier, for example), but this should get the job done regardless of your environment.
诚然,这是获取Book节点子节点的不同节点名称列表的基本方法,但您没有在环境中指定太多其他方式(如果您有 3.5,您可以使用 LINQ to XML 来实现这一点)例如,稍微漂亮一点),但是无论您的环境如何,这都应该可以完成工作。
回答by J Mills
I agree with Adam, the ideal condition is to have a schema that defines the content of xml document. However, sometimes this is not possible. Here is a simple method for iterating all of the nodes of an xml document and using a dictionary to store the unique local names. I like to keep track of the depth of each local name, so I use a list of int to store the depth. Note that the XmlReader is "easy on the memory" since it does not load the entire document as the XmlDocument does. In some instances it makes little difference because the size of the xml data is small. In the following example, an 18.5MB file is read with an XmlReader. Using an XmlDocument to load this data would have been less effecient than using an XmlReader to read and sample its contents.
我同意 Adam,理想的条件是拥有一个定义 xml 文档内容的模式。然而,有时这是不可能的。这是一个简单的方法,用于迭代 xml 文档的所有节点并使用字典来存储唯一的本地名称。我喜欢跟踪每个本地名称的深度,因此我使用一个 int 列表来存储深度。请注意,XmlReader“容易占用内存”,因为它不像 XmlDocument 那样加载整个文档。在某些情况下,它没有什么区别,因为 xml 数据的大小很小。在以下示例中,使用 XmlReader 读取 18.5MB 的文件。使用 XmlDocument 加载此数据的效率低于使用 XmlReader 读取和采样其内容的效率。
string documentPath = @"C:\Docs\cim_schema_2.18.1-Final-XMLAll\all_classes.xml";
Dictionary<string, List<int>> nodeTable = new Dictionary<string, List<int>>();
using (XmlReader reader = XmlReader.Create(documentPath))
{
while (!reader.EOF)
{
if (reader.NodeType == XmlNodeType.Element)
{
if (!nodeTable.ContainsKey(reader.LocalName))
{
nodeTable.Add(reader.LocalName, new List<int>(new int[] { reader.Depth }));
}
else if (!nodeTable[reader.LocalName].Contains(reader.Depth))
{
nodeTable[reader.LocalName].Add(reader.Depth);
}
}
reader.Read();
}
}
Console.WriteLine("The node table has {0} items.",nodeTable.Count);
foreach (KeyValuePair<string, List<int>> kv in nodeTable)
{
Console.WriteLine("{0} [{1}]",kv.Key, kv.Value.Count);
for (int i = 0; i < kv.Value.Count; i++)
{
if (i < kv.Value.Count-1)
{
Console.Write("{0}, ", kv.Value[i]);
}
else
{
Console.WriteLine(kv.Value[i]);
}
}
}
回答by Nam G VU
An online tool I find here can extract those elements 's names beautifully - just uploading the XML file and they print the names as a result webpage.
我在这里找到的一个在线工具可以很好地提取这些元素的名称 - 只需上传 XML 文件,它们就会将名称打印为结果网页。
http://taporware.ualberta.ca/~taporware/xmlTools/listxml.shtml
http://taporware.ualberta.ca/~taporware/xmlTools/listxml.shtml
回答by Chintan Patel
If BookStoreis ur root element then u can try following code
如果BookStore是您的根元素,那么您可以尝试以下代码
XmlDocument doc = new XmlDocument();
doc.Load(configPath);
XmlNodeList list = doc.DocumentElement.GetElementsByTagName("Book");
if (list.Count != 0)
{
for (int i = 0; i < list[0].ChildNodes.Count; i++)
{
XmlNode child = list[0].ChildNodes[i];
}
}


