简体   繁体   中英

Manipulating XML names and values from file in C#

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,

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);
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM