使用Linq从xml文件读取值 [英] Reading values from xml file with Linq

查看:56
本文介绍了使用Linq从xml文件读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从xml文件读取值时遇到麻烦.这是xml文件:

I'm having troubles reading values from an xml file. Here is the xml file:

<root>
    <defaultGroups name="Sikker">
        <group name="0ASK" />
        <group name="0ASKAPP" />
        <group name="0ASKFELLES" />
        <group name="0SYSAPP" />
        <group name="0SYSAPPoffice" />
        <group name="10WTS" />
    </defaultGroups>
    <defaultGroups name="Intern">
        <group name="11WTS" />
        <group name="1ASK" />
        <group name="1ASKAPP" />
        <group name="1ASKFELLES" />
        <group name="Domain Users" />
        <group name="Askvoll brukere" />
        <group name="1SYSAPP" />
        <group name="1SYSAPPAdobeReader" />
        <group name="1SYSAPPEXCEL" />
        <group name="1SYSAPPIEXPLORER" />
        <group name="1SYSAPPOUTLOOK" />
        <group name="1SYSAPPPOWERPOINT" />
        <group name="1SYSAPPWORD" />
    </defaultGroups>
</root>

使用下面显示的功能,我应该只从< defaultGroups name ="Sikker"> 中读取值.我确实得到了第一个值:"0ASK",但没有得到.有人可以帮我吗?(我是Linq的新手)

With the function shown below, I'm supposed to only read the values from <defaultGroups name="Sikker">. I do get the first value: "0ASK", but not the rest. Can someone please help me with this? (I'm new to Linq)

这是我使用的C#函数:

This is the C# function I use:

public string GetSikkerSoneDefaultGroups(string companyName)
    {
        string sikkerSone = "";

        XDocument doc = XDocument.Load("xml\\defaults\\" + companyName + ".xml");
        var groups = from defaultGroups in doc.Descendants("defaultGroups")
                     where defaultGroups.Attribute("name").Value == "Sikker"
                     select new
                     {                             
                         g = defaultGroups.Element("group").Attribute("name").Value
                     };

        foreach (var group in groups)
        {
            sikkerSone += group.g + ";";
        }

        doc = null;

        return sikkerSone;

    }

推荐答案

您正在使用:

g = defaultGroups.Element("group").Attribute("name").Value

仅选择defaultGroups的第一个子元素.我认为我们可以将其简化很多,因为您接近它的方式将需要一个子查询.为什么不直接获取组元素?

which only selects the first child element of defaultGroups. I think we can simplify this quite a bit, as the way you're approaching it you would need a subquery. Why not get the group elements directly?

var groups = from defaultGroup in doc.Descendants("group")
             where defaultGroup.Parent.Attribute("name").Value == "Sikker"
             select defaultGroup.Attribute("name").Value;


// Make it into a string
foreach (var group in groups)
{
     sikkerSone += group + ";";
}

这篇关于使用Linq从xml文件读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆