2

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?

2
  • 1
    Which message? All of them? Do you want to concat them all into one string or return an array of all the message strings? Commented Dec 6, 2012 at 8:45
  • want to return to as an array of string Commented Dec 6, 2012 at 8:46

2 Answers 2

6
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.

Sign up to request clarification or add additional context in comments.

4 Comments

How to check this with the "id"?
@VaraPrasad.M updated samples with filtering. If you need single element, than use .SingleOrDefalult() operator
Now if we got other than "Address" and now i want to retrieve "Email" then how can i get. updated question
@VaraPrasad.M same approach - .Descendants("Exeption").Where(e => (string)e.Attribute("Name") == "Email").Elements("Error")...`
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.