开发者

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 t开发者_StackOverflow中文版o 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜