Search code examples
c#xmlxmlreadermovies

Find a node by attribute and return a different attribute's value from that same node


I have for example the following data in an xml file:

<Critic-List>
  <bruce-bennett>
   <Movie Title="White House Down (2013)" Score="C+" Like="false"/>
   <Movie Title="Despicable Me 2 (2013)" Score="A-" Like="true"/>
   <Movie Title="World War Z (2013)" Score="B+" Like="true"/>
   <Movie Title="Man of Steel (2013)" Score="B+" Like="true"/>

how do i write a code which

  1. selects a node by attribute- say attribute(title)="Despicable Me 2 (2013)"
  2. and from that selected node gives the value for another attribute of that node- for instance: attribute(like)... (which in this case would return "true")

XML readers in C# seems more geared towards returning "inner text" rather than attribute values, I'm wondering if maybe I should have stored my xml data in inner text rather than attributes.. to me it would be much more convenient to retrieve the data values of attributes, but i'm not sure if those parameters exist...

any help or suggested reading would be much appreciated!


Solution

  • I'm not sure what method your trying to use to get the result, LINQ to XML is definitely a good way to do so. If you're trying to use XPath, here is how you would achieve the same outcome.

    var xml = @"<Critic-List>
      <bruce-bennett>
       <Movie Title=""White House Down (2013)"" Score=""C+"" Like=""false""/>
       <Movie Title=""Despicable Me 2 (2013)"" Score=""A-"" Like=""true""/>
       <Movie Title=""World War Z (2013)"" Score=""B+"" Like=""true""/>
       <Movie Title=""Man of Steel (2013)"" Score=""B+"" Like=""true""/>    
      </bruce-bennett>
      </Critic-List>";
    XElement doc = XElement.Parse(xml);
    
    var node = doc.XPathSelectElement("//Movie[@Title='Despicable Me 2 (2013)']");
    var like = node.Attribute("Like").Value;
    

    The w3schools is a good site to get some tutorials on XPath. Options are always a good way to expand your horizons.