1
<tests>
  <test id ="1">
    <name> peter </name>
    <age> 23 </age>
    <informations> bla bla </informations>
  </test>
  <test id ="41">
    <name> besd </name>
    <age> 54 </age>
    <informations> some other text </informations>
  </test>
  <test id ="57">
    <name> john </name>
    <age> 61 </age>
    <informations> vintage </informations>
  </test>
  <test id ="67">
    <name> claude </name>
    <age> 11 </age>
    <informations> motivation </informations>
  </test>
</tests>

I managed to get all the above informations inside an XDocument xInformations.

  List<string> testIds = new List<string>();
  testIds = xInformations.Descendants("test").Select(x => (string)x.Attribute("id")).ToList();

And now, I do want using foreach, to read and save all the informations for each id:

foreach (string extId in testIds.Distinct())
{
     /// how can I take step by step the name, age, informations for all test cases ?
}

How can I achieve this?

Bernard Vander Beken
  • 4,848
  • 5
  • 54
  • 76
Florin M.
  • 2,159
  • 4
  • 39
  • 97
  • I didn't find using XDocument – Florin M. Aug 04 '17 at 09:23
  • Ah snap, sorry :) – Renatas M. Aug 04 '17 at 09:25
  • Anyways there are plenty examples you can find: [here](https://stackoverflow.com/questions/752271/how-to-get-xml-node-from-xdocument), [here](https://stackoverflow.com/questions/4148223/xdocument-picking-the-right-nodes?rq=1) and many more. Have you tried any of them? – Renatas M. Aug 04 '17 at 09:30
  • @FlorinM. One you saw the below image it's getting value from attribute. I was Checked What is Your Exact Exception. – umasankar Aug 04 '17 at 10:02

3 Answers3

3

Create anonymous(or introduce own class) instance and use it in foreach loop

var tests = xInformations.Descendants("test")
                         .Select(x => 
                         {
                             new 
                             {
                                 Id = x.Attribute("id")?.Value,
                                 Name = x.Element("name").Value,
                                 Age = x.Element("age").Value,
                                 Info = x.Element("informations").Value
                             }
                         });

foreach(var test in tests)
{
    // test.Id
    // test.Name
    // test.Age
    // test.Info       
}

Or if schema of xml file remain same you can use clearer code with XmlSerializer

[XmlType("tests")]
public class Tests
{
    public List<Test> Tests { get; set; }
}

[XmlType("test")]
public class Test
{
    [XmlAttribute("id")]
    public int Id { get; set; }
    [XmlElement("name")]
    public string Name { get; set; }
    [XmlElement("age")]
    public int Age { get; set; }
    [XmlElement("informations")]
    public string Info { get; set; }
}

var serializer = new XmlSerializer(typeof(Tests));
Tests tests = null;
using (var reader = new StreamReader(pathToXmlFile))
{
    tests = (Tests)serializer.Deserialize(reader);
}

// use tests for your needs
foreach(var test in tests.Tests)
{
    // test.Id
}
Fabio
  • 31,528
  • 4
  • 33
  • 72
0

This is a way you could do it

        // path to file
        string path = @"C:\t\1.txt";
        XDocument _doc = XDocument.Load(path);

        List<XElement> testIds = new List<XElement>();
        // get all test elements
        testIds = _doc.Descendants("test").ToList();

        // loop true test elements
        foreach (XElement extId in testIds.Distinct())
        {
            // get element values

            string id = extId.Attribute("id").Value;
            string name = extId.Element("name").Value;
            string age = extId.Element("age").Value;
            string info = extId.Element("informations").Value;
            Console.WriteLine(id+ "," + name + ", " + " " + age + ", " + info);
        }
Timon Post
  • 2,779
  • 1
  • 17
  • 32
0
string path = @"D:\1.txt";
  XDocument _doc = XDocument.Load(path);

  List<XElement> testIds = new List<XElement>();

  testIds = _doc.Descendants("test").ToList();


  foreach (XElement extId in testIds.Distinct())
  {
     // get element values
        string id = extId.Attribute("id").Value;
        string name = extId.Element("name").Value;
        string age = extId.Element("age").Value;
        string info = extId.Element("informations").Value;
        Console.WriteLine(name + ", " + " " + age + ", " + info);
  }

string id = extId.Attribute("id").Value;

enter image description here

The Attribute method is used for get the values of the node inside attribute value.

I was Checked the data is getting from attribute properly.

umasankar
  • 599
  • 1
  • 9
  • 28
  • In case when "id" attribute missing, line `exId.Attrbute("id").Value` will throw `NullReferenceException`, because `Element.Attribute` method will return `null` – Fabio Aug 04 '17 at 10:06
  • @Fabio in given xml all elements having Id attribute. So, I don't Check null.Thanks for Comment – umasankar Aug 04 '17 at 10:08