Vara Prasad.M
Vara Prasad.M

Reputation: 1550

Retrieve the node values from XML file in LINQ and C#

I have a xml file and I want to retrieve the values from the message attributes into a string array from the below structure:

<Exceptions>
  <Exception Name="Address">
    <Error id="Line1" message="Address Line 1 is required"/>
    <Error id="Line1Length" message="Address Line 1 must be in-between 1 and 50"/>
    <Error id="Line2Length" message="Address Line 2 must be in-between 1 and 50"/>
  </Exception>
  <Exception Name="Email">
    <Error id="Line1" message="Email is required"/>
  </Exception>
</Exceptions>

How can I do this using LINQ-XML?

Upvotes: 2

Views: 705

Answers (2)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Something like this:

string xml = "<Exceptions>
  <Exception Name='Address'>
    <Error id='Line1' message='Address Line 1 is required'/>
    <Error id='Line1Length' message='Address Line 1 must be in-between 1 and 50'/>
    <Error id='Line2Length' message='Address Line 2 must be in-between 1 and 50'/>
  </Exception>
</Exceptions>";

var document = XDocument.Load(new XmlTextReader(xml));
var messages = document.Descendants("Error").Attributes("message").Select(a => a.Value);

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

string id = "Line1Length";
XDocument xdoc = XDocument.Load(path_to_xml);
var messages = xdoc.Descendants("Error")
                   .Where(e => (string)e.Attribute("id") == id)
                   .Select(e => (string)e.Attribute("message"));

Also if you didn't provide full structure of xml file, then:

var messages = xdoc.Descendants("Exceptions")
                   .Element("Exception")
                   .Elements("Error")
                   .Where(e => (string)e.Attribute("id") == id)
                   .Select(e => (string)e.Attribute("message"));

BTW this will return IEnumerable<string> messages. If you want array, then apply ToArray() after select operator.

Upvotes: 6

Related Questions