1

I know this is a common question, but I have a requirement where I need to read values from XML file. Sturcture of the XML file is

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <uielements>
    <Page name ="Page1">
      <element name="ele_child123" value="Search123" type="type1"/>
      <element name="ele_child124" value="Search124" type="type2"/>
      <element name="ele_child125" value="Search125" type="type3"/>
      <element name="ele_child126" value="Search126" type="type4"/>
      </Page>
      <Page name ="Page2">
      <element name="ele_child123" value="Search123" type="type1"/>
      <element name="ele_child124" value="Search124" type="type2"/>
      <element name="ele_child125" value="Search125" type="type3"/>
      <element name="ele_child126" value="Search126" type="type4"/>
      </Page>
      <Page name ="Page3">
      <element name="ele_child123" value="Search123" type="type1"/>
      <element name="ele_child124" value="Search124" type="type2"/>
      <element name="ele_child125" value="Search125" type="type3"/>
      <element name="ele_child126" value="Search126" type="type4"/>
      </Page>
      <Page name ="Page4">
      <element name="ele_child123" value="Search123" type="type1"/>
      <element name="ele_child124" value="Search124" type="type2"/>
      <element name="ele_child125" value="Search125" type="type3"/>
      <element name="ele_child126" value="Search126" type="type4"/>
      </Page>
  </uielements>
</root>

I need to get value of the 'value' attribute, based on the page name and element name.

Page name will be unique in one file, while element name can be duplicate but unique inside one page name.

Earlier, I was using something like below code for getting this value, but now I have one more attribute i.e. Page name and below logic is no more working.

string name = "'ele_child123'";
string find = "//element[@name=" + name + "]/@value";
string attrVal = xmldoc.SelectSingleNode(find).Value;
2

Using a similar logic to what you already have I would simple loop through based on your xdoc.

using System.Xml.Linq;
XDocument xdoc = XDocument.Load("uielements.XML"); 

string name = "'ele_child123'";
string find = "//element[@name=" + name + "]";

        foreach (var childElem in xdoc.XPathSelectElements(find))
        {
            string childName = childElem.Element("value").Value;
            Console.WriteLine(childName);
        }
|improve this answer|||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.