C# how can I get all elements name from a xml file

Related searches

I'd like to get all the element name from a xml file, for example the xml file is,

<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

I tried several ways, but doesn't work, how can I do it?

Well, with XDocument and LINQ-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.

XmlDocument.GetElementsByTagName Method (System.Xml , Returns an XmlNodeList containing a list of all descendant elements that match the specified name. C#. public virtual System.Xml.XmlNodeList GetElementsByTagName (string name); abstract member GetElementsByTagName : string -> System.Xml.XmlNodeList override this.GetElementsByTagName : string -> System.Xml.XmlNodeList. Public Overridable Function GetElementsByTagName (name As String) As XmlNodeList.

Using 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

XmlElement.GetElementsByTagName Method (System.Xml , Returns an XmlNodeList containing a list of all descendant elements that match the specified name. If you're simply trying to find the "next" or "previous" iteration of a single node, you can do the following and then compare it to the name. XmlNode current = doc.SelectSingleNode("Fruits").SelectSingleNode("Red_fruits"); XmlNode previous = current.NextSibling; XmlNode next = current.NextSibling;

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.

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]);
        }
    }
}

Select XML Nodes by Name [C#], To find nodes in an XML file you can use XPath expressions. Method XmlNode. To get all <Name> nodes use XPath expression /Names/Name . The first slash � Read elements from XML file. Ask Question I'm trying to read from an XML file and use that to populate a question object I've created. I have look at this How

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 Book node'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.

XML Manipulation In C#, Its self-documenting format describes the structure and field names as well as specific values. The following is the LINQ to XML(XDocument) class hierarchy, which ://stackoverflow.com/questions/2013165/add-an-element-to-xml-file For instance, we have a list of projects and we want it in XML format. This topic demonstrates the Elements method. This method retrieves a collection of the child elements of an element. Example. This example iterates through the child elements of the purchaseOrder element. This example uses the following XML document: Sample XML File: Typical Purchase Order (LINQ to XML).

If you're using C# 3.0, you can do the following:

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();

How To Select XML Node By Name In C#, What is XPath? XPath is a path expression to select the nodes or node-sets in an XML document. Code Now, we have the� When you call one of the methods that return IEnumerable<T> of XElement, you can filter on the element name. Example. This example retrieves a collection of descendants that is filtered to contain only descendants with the specified name. This example uses the following XML document: Sample XML File: Typical Purchase Order (LINQ to XML).

XDocument(System.Xml.Linq) is from the LINQ to XML API and XmlDocument(System.Xml.XmlDocument) is the standard DOM-style API for XML. If you're using .NET version 3.0 or lower, you have to use XmlDocument, the classic DOM API. On the other hand, if you are using .NET version 3.5 onwards, you need to use XDocument.

Please be careful that your behaviour doesn't get perceived as "point farming" as it could be reported as abuse of the site. If someone else's solution has helped you make sure that you credit them properly - you can accept more than one solution if necessary. For example: How to pass the json string to client.postasync() method in C#?

How to retrieve the value of an element (LINQ to XML) (C#) 07/20/2015; 3 minutes to read +5; In this article. This article shows how to get the value of elements. There are two main ways to get the value: Cast an XElement or an XAttribute to the desired type. The explicit conversion operator then converts the contents of the element or

Comments
  • Thanks a lot. Im not famliar with LINQ-XML. But it works very well. One more thing, I updated the question above. how can I only get the child nodes' name under <BookStore> element.
  • If you mean under "Book" (as per updated question) - something like: doc.Root.Element("Book").DescendantNodes()...
  • Yes, that's what I mean. And the code is working, thank u again!
  • @MarcGravell can we get entire node collection using this approach, i mean entire nodes with specific name
  • @Chintan_Patel points out below that you can do it in a single line with the GetElementsByTagName method
  • There is no such thing as C# 3.5; that uses C# 3.0 and .NET 3.5, though.
  • Great answer. How would you count the number of times each tag appears?