Home > database >  If name attribute is X then get content of value attribute
If name attribute is X then get content of value attribute

Time:06-08

I am struggling with code in C# for getting value depending on the first argument from XML:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
    <TestRunParameters>
        <Parameter name="browser" value="chrome" />
        <Parameter name="browserVersion" value="101.0"/>
        <Parameter name="os" value="WIN11"/>
        <Parameter name="build" value=""/>
    </TestRunParameters>
</RunSettings>

I would like to check if the parameter name is browser then take its content from value. I am able to get this values by SelectNodes("//@value") and node[0].Value but I am wondering if there is another way of getting those values without specifing the position. Here is my code:

var filename = @"../../../browser.runsettings";
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(filename);

            XmlNodeList node = xmlDoc.SelectNodes("//@value");
            var browserValue = node[0].Value;

Thanks in advance for help

CodePudding user response:

I think you should cycle thought them and check if the name is Browser and then use the value. Something like this should do it

foreach (XmlNode node in nodes)
            {
                if (node.Name != "Browser") continue;
                
                browserValue = node.Value;
                break;
            }

CodePudding user response:

You can also get single node by using .SelectSingleNode() instead of using .SelectNodes()

var filename = @"../../../browser.runsettings";
var xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
XmlNode node = xmlDoc.SelectSingleNode("//@value");
var browserValue = node.Value;
  • Related