简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM