Home > Mobile >  C# - Can I select the value of an XML attribute by searching for a second attribute?
C# - Can I select the value of an XML attribute by searching for a second attribute?

Time:11-30

I want to select the value of the "data" attribute where the "key" attribute matches a specific search.

The XML file will look like this.

<connections>
  <production>
    <connection key="KEY1" data="value1" />
    <connection key="KEY2" data="value2" />
    <connection key="KEY3" data="value3" />
  </production>
</connections>

So is there a way to return the value of the data attribute by searching for key = key1 for example?

CodePudding user response:

You could do something like this if you wanted to avoid using XPath.

using System.Xml.Linq;

var xmlStr = File.ReadAllText("Testfile.xml");
XElement root = XElement.Parse(xmlStr);
var data = root.Element("production")
    .Elements().Where(x => x.Attribute("key").Value == "KEY1")
    .Select(x=>x.Attribute("data").Value)
    .First();
Console.WriteLine(data);

CodePudding user response:

Try this, using System.Xml you can read the xml file in question and iterate through the nodes to look for your value.

private void YOUR_METHOD_NAME()
{
    // Call GetXml method which returns the result in the form of string
    string result = GetXml("xmlfile.xml", "KEY2");
    Debug.WriteLine(result);
}

private string GetXml(string filePath, string searchKey)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(filePath);

    XmlNodeList nodes = doc.SelectSingleNode("//connections/production").ChildNodes;

    string output = string.Empty;
    foreach (XmlNode node in nodes)
    {
        if (node.Attributes["key"].Value == searchKey)
        {
            output = node.Attributes["data"].Value;
        }
        else
        {
            continue;
        }
    }

    return output;
}
  • Related