Reading Xml

Yusuf 791 Reputation points
2022-10-12T13:34:06.393+00:00

Hi
I generated this xml file,

<?xml version="1.0" encoding="utf-8"?>  
<Root>  
 <Automobile>  
 <Country>Germany</Country>  
 <Manufacturers>Audi</Manufacturers>  
 <Manufacturers>BMW</Manufacturers>  
 <Manufacturers>Mercedes-Benz</Manufacturers>  
 </Automobile>  
 <Automobile>  
 <Country>United States</Country>  
 <Manufacturers>Jeep</Manufacturers>  
 <Manufacturers>Ford</Manufacturers>  
 <Manufacturers>Dodge</Manufacturers>  
 </Automobile>  
 <Automobile>  
 <Country>France</Country>  
 </Automobile>  
 <Automobile>  
 <Country></Country>  
 <Manufacturers></Manufacturers>  
 </Automobile>  
 <Automobile>  
 </Automobile>  
</Root>  

What is the easiest way to loop through XML using XmlDocument, so the output of the data be as :

Germany
Audi
BMW
Mercedes-Benz

United States
Jeep
Ford
Dodge

France

I can also add attributes to element to determine if item has children
Thanks in advance

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,097 questions
{count} votes

Accepted answer
  1. Jack J Jun 24,606 Reputation points Microsoft Vendor
    2022-10-13T01:55:27.253+00:00

    @Yusuf , Welcome to Microsoft Q&A, you could try to use XmlDocument.SelectNodes to get your wanted data by looping through the xml file.

    Here is a code example you could refer to.

     static void Main(string[] args)  
            {  
                XmlDocument doc = new XmlDocument();  
                doc.Load(@"test.xml");  
                foreach (XmlNode item in doc.SelectNodes("descendant::Automobile"))  
                {  
                    foreach (XmlNode node in item.ChildNodes)  
                    {  
                        if(node!=null)  
                        {  
                            Console.WriteLine(node.InnerText);  
                        }  
                    }  
                    Console.WriteLine("  ");  
                  
                }  
            }  
    

    Tested result:

    249839-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.