简体   繁体   English

从LINQ和C#中的XML文件中检索节点值

[英]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: 我有一个xml文件,我想将message属性中的值从以下结构中检索到string数组中:

<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? 我怎么能用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: 另外,如果您未提供xml文件的完整结构,则:

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 . 顺便说一句,这将返回IEnumerable<string> messages If you want array, then apply ToArray() after select operator. 如果需要数组,请在选择运算符之后应用ToArray()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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