bearaman
bearaman

Reputation: 1091

Return all matching XML nodes using LINQ

<?xml version='1.0' encoding='utf-8'?>
<automationSettings>

<VM name="DE-123" language="de" powerOn="true">
    <vmClients>
        <vmClient name="KO-123" language="ko"/>
                    <vmClient name="US-123" language="en"/>
                    <vmClient name="FR-123" language="fr"/>
    </vmClients>
</VM>

<VM name="ES-123" language="en" powerOn="true">
    <vmClients>
        <vmClient name="IT-123" language="it"/>
        <vmClient name="JA-123" language="ja"/>
    </vmClients>
</VM>

</automationSettings>

I have a C# method that is supposed to return all values of vmClient name attribute when the VM element has a matching name. For example, I want to get the vmClient names of the VM with name="DE-123". Here's the code I tried but it's not returning anything. What am I doing wrong? Thanks for any help offered.

public static void GetClientsList(string systemName)
    {
        systemsFilePath = "text.xml";
        string listOfClients = string.Empty;

        try
        {
            var xdoc = XDocument.Load(systemsFilePath);
            var query = from vm in xdoc.Root.Descendants("VM").Descendants("vmClients").Elements()
                        where vm.Attribute("name").Value == systemName
                        select new
                        {
                            Name = (string)vm.Attribute("name").Value
                        };

            var vms = query.ToList();

            for (int i = 0; i < vms.Count; i++)
            {
                listOfClients += vms[i].Name + " ";
            }

            Global.epoClients = listOfClients;
        }

        catch (Exception ex)
        {
            Console.WriteLine("GetClientsList exception: " + ex.Message);
        }
    }
}

Upvotes: 0

Views: 688

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500855

I suspect you actually want:

var query = xdoc.Root.Descendants("VM")
                .Where(vm => (string) vm.Attribute("name") == systemName)
                .Descendants("vmClient")
                .Select(vmClient => (string) vmClient.Attribute("name"));

Note how we're testing the VM element, not the vmClients element.

Upvotes: 1

Related Questions