1

i have an xml file which contain some data like:

<?xml version="1.0" encoding="utf-8" ?>
<permission>
    <CP name="My Messages">
        <field name="name"/>
        <field name="age"/>
        <field name="ID"/>
    </CP>
    <field name="time"/>
    <CP name="My Attandance">
    </CP>    
</permission>

by using my winforms app. i want to get the fields of "My Messages" in my code to further use, means i get the values and be able to even assign in to string or as control name, also i want to know the total count of it in C# code,

2 Answers 2

5

Personally I like using XPath:

using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

class Program
{
    static void Main()
    {
        var values = from field in XDocument.Load("test.xml")
                          .XPathSelectElements("//CP[@name='My Messages']/field")
                     where field.Attribute("name") != null
                     select field.Attribute("name").Value;
        Console.WriteLine("total values: {0}", values.Count());
        foreach (var value in values)
        {
            Console.WriteLine(value);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

That will give you the IEnumerable of field Values.

var values = from f in
                  ((from cp in document.Root.Elements()
                    where cp.Attribute("name").Value == "My Messages"
                    select cp).First()).Elements()
             select f.Attribute("Name").Value;

Count is easier:

var values = (from cp in document.Root.Elements()
                        where cp.Attribute("name").Value == "My Messages"
                        select cp).First()).Elements().Count();

Not very elegant, though.

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.