XML Child nodes by name

Festus Hagen 41 Reputation points
2021-02-11T23:07:39.153+00:00

Working on my non existent C# XML skills ...

I sat down this morning and whipped up the following in about 10 minutes ...

The XML

        <Format version="0.0.1">
          <Product>
            <Title>Title 5</Title>
          </Product>
          <Product>
            <Title>Title 4</Title>
          </Product>
          <Product>
            <Title>Title 1</Title>
          </Product>
          <Product>
            <Title>Title 2</Title>
          </Product>
          <Product>
            <Title>Title 3</Title>
          </Product>
          <Property>
            <Name>Property 1</Name>
            <Setting>0xB100</Setting>
          </Property>
          <Property>
            <Name>Property 3</Name>
            <Setting>0xCFBA</Setting>
          </Property>
          <Property>
            <Name>Property 2</Name>
            <Setting>0xF824</Setting>
          </Property>
        </Format>

The Code

                    int i = 0;
                    XmlDataDocument xmlDoc = new XmlDataDocument();

                    textBox1.Text = String.Empty;

                    using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read))
                    {
                        xmlDoc.Load(fs);
                    }

                    XmlNodeList xmlNodeProducts = xmlDoc.GetElementsByTagName("Product");
                    textBox1.Text += "Products:" + Environment.NewLine;
                    for (i = 0; i < xmlNodeProducts.Count; i++)
                    {
                        // I would like to get the ChildNode by Name not Index. For example by "Title" or "Name" or "Setting".
                        textBox1.Text += "\t" + xmlNodeProducts[i].ChildNodes.Item(0).InnerText.Trim() + Environment.NewLine;
                    }

                    XmlNodeList xmlNodeProperties = xmlDoc.GetElementsByTagName("Property");
                    textBox1.Text += Environment.NewLine + "Properties:" + Environment.NewLine;
                    for (i = 0; i < xmlNodeProperties.Count; i++)
                    {
                        // I would like to get the ChildNode by Name not Index. For example by "Title" or "Name" or "Setting".
                        textBox1.Text += "\t" + xmlNodeProperties[i].ChildNodes.Item(0).InnerText.Trim() + Environment.NewLine;
                    }

Does just like I want for the time being with one minor exception ...
I'd like to be able to get the ChildNode by name ... See comments in above code.

However, XmlDataDocument is obsolete ... So I have spent the rest of the day trying to do this same thing in a non obsolete fashion to no avail.

Ultimately this is going to be an editor/diff tool for the xml file.

Any guidance would be much appreciated.

Thank You!

P.S. This Site and Editor is almost a worse disaster then the previous one ... New is not always better, this new Microsoft Q/A site is a good example of that.

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.
10,836 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Yitzhak Khabinsky 25,851 Reputation points
    2021-02-12T02:26:54.507+00:00

    Definitely, it is much better to use LINQ to XML API. It is available in the .Net Framework since 2007.

    c#

    void Main()
    {
     const string xmlFileName = @"e:\temp\InputFormat.xml";
    
     XDocument xdoc = XDocument.Load(xmlFileName);
    
     foreach (XElement elem in xdoc.Descendants("Product"))
     {
     Console.WriteLine("Title: {0}", elem.Element("Title")?.Value);
     }
    
     foreach (XElement elem in xdoc.Descendants("Property"))
     {
     Console.WriteLine("Name: {0}, Setting: {1}"
     , elem.Element("Name")?.Value
     , elem.Element("Setting")?.Value);
     }
    }
    

    Output

    Title: Title 5
    Title: Title 4
    Title: Title 1
    Title: Title 2
    Title: Title 3
    Name: Property 1, Setting: 0xB100
    Name: Property 3, Setting: 0xCFBA
    Name: Property 2, Setting: 0xF824
    
    1 person found this answer helpful.
    0 comments No comments

  2. Xingyu Zhao-MSFT 5,366 Reputation points
    2021-02-12T06:45:26.993+00:00

    Hi @Festus Hagen ,
    You can also use ‘XmlDocument’ to read xml.

                XmlDocument doc = new XmlDocument();  
                doc.Load(xmlFilePath);  
      
                textBox1.Text += "Products:" + Environment.NewLine;  
      
                XmlNodeList productNodeList = doc.SelectNodes("/Format/Product");  
                foreach (XmlNode productNode in productNodeList)  
                {  
                    textBox1.Text += "".PadRight(4) + productNode.FirstChild.Name + " : " + productNode.FirstChild.InnerText + Environment.NewLine;  
                }  
      
                textBox1.Text += Environment.NewLine + "Properties:" + Environment.NewLine;  
                XmlNodeList PropertyNodeList = doc.SelectNodes("/Format/Property");  
                foreach (XmlNode propertyNode in PropertyNodeList)  
                {  
                    textBox1.Text += "".PadRight(4) + propertyNode.Name + " : " + Environment.NewLine;  
                    foreach (XmlNode propertyChild in propertyNode.ChildNodes)  
                    {  
                        textBox1.Text += "".PadRight(8) + propertyChild.Name + " : " + propertyChild.InnerText + Environment.NewLine;  
                    }  
                }  
    

    Result:

    Products:  
        Title : Title 5  
        Title : Title 4  
        Title : Title 1  
        Title : Title 2  
        Title : Title 3  
      
    Properties:  
        Property :   
            Name : Property 1  
            Setting : 0xB100  
        Property :   
            Name : Property 3  
            Setting : 0xCFBA  
        Property :   
            Name : Property 2  
            Setting : 0xF824  
    

    Hope it could be helpful.

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    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.

    0 comments No comments

  3. Festus Hagen 41 Reputation points
    2021-02-12T12:57:11.667+00:00

    Both @Yitzhak Khabinsky and @Xingyu Zhao-MSFT deserve the Accepted Answer award!
    However this ignorant dictator site will not allow that ...

    Thank you both!

    I assure you, what goes around, comes around! I also volunteer most all of my time answering questions on forums where I'm skilled!
    So, again, Thank you for doing what you do!


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.