2

This is my XML file. I need to select one test element and get all attributes name from its result child nodes.

<?xml version="1.0" encoding="UTF-8"?>
<summary>
  <test>
    <id>test 1</id>   
    <result value="-45">330</result>
    <result value="0">300</result>
    <result value="45">340</result>
  </test>
  <test>
    <id>test 3</id>    
    <result value="-45">330</result>
    <result value="0">300</result>
    <result value="45">340</result>
  </test>
</summary>

I wrote below code. but repeat same values and I want to stop it.

XmlDocument xd = new XmlDocument();
xd.Load(_xmlFilePath);

XmlNodeList nodelist = xd.GetElementsByTagName("result");

foreach (XmlNode node in nodelist)
    {
        string attrVal = node.Attributes["value"].Value;
        Console.WriteLine(attrVal);
    }

Any suggestion is appreciated.

Thanks.

2
  • Can u show what is expected value of nodelist and output of attrVal Commented Jan 10, 2017 at 8:36
  • Output should be -45,0,45 Commented Jan 10, 2017 at 8:38

2 Answers 2

2

You can use LINQ to Xml with XDocument class

var doc = XDocument.Load(_xmlFilePath);

var distinctResults = doc.Descendants("result")
                         .Select(element => element.Attribute("value").Value)
                         .Distinct();

foreach(var result in distinctResults)
{
    Console.WriteLine(result);
}

Or with using of HashSet<string>

var results = doc.Descendants("result")
                 .Select(element => element.Attribute("value").Value);

var distinctResults = new HashSet<string>(results); 

foreach(var result in distinctResults)
{
    Console.WriteLine(result);
}
Sign up to request clarification or add additional context in comments.

2 Comments

'System.Xml.XmlDocument' does not contain a definition for 'Descendants' and no extension method 'Descendants' accepting a first argument of type 'System.Xml.XmlDocument' could be found
Use XDocument class instead of XmlDocument
0

Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication34
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);

            string id = "test 1";

            var results = doc.Descendants("test").Where(x => (string)x.Element("id") == id).FirstOrDefault().Elements("result").Select(x => new
            {
                angle = (int)x.Attribute("value"),
                length = (int)x
            }).ToList();

        }


    }


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.