Reading values ​​from an xml file using Linq

I am having trouble 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>

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

This is the C # function that 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;

    }
+3
source share
2 answers

You are using:

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

which selects only the first child of the default groups. I think that we can simplify this quite a bit, since you are approaching it, you will need a subquery. Why not get group members 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 + ";";
}
+2
source
string sikkerSone = string.Join(";",
   (from dg in doc.Descendants("defaultGroups")
    where dg.Attribute("name") == "Sikker"
    from g in dg.Elements("group")
    select (string)g.Attribute("name"))
   .ToArray());
0
source

Source: https://habr.com/ru/post/1716619/


All Articles