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

时间:2012-12-06 08:42:33

标签: c# xml linq linq-to-xml

我有一个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>

如何使用LINQ-XML执行此操作?

2 个答案:

答案 0 :(得分: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"));

另外,如果你没有提供xml文件的完整结构,那么:

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

BTW 这将返回IEnumerable<string> messages。如果您需要数组,请在选择运算符后应用ToArray()

答案 1 :(得分:1)

这样的事情:

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