【问题标题】:Reading XML attribute value based on another attribute基于另一个属性读取 XML 属性值
【发布时间】:2013-04-25 21:10:43
【问题描述】:

我正在尝试根据我传递的错误代码检索错误消息。我如何使用 linq 做到这一点?

这是我的 xml 文档布局

<?xml version="1.0" encoding="utf-8" ?>
<errors>
  <error code="101" message="Our Database is currently experience problems!">   
  </error>
</errors>

这是我在 C# 中的加载代码

XmlDocument doc = new XmlDocument();
doc.Load(HttpContext.Current.Server.MapPath("/App_Data/ErrorCodes.xml"));

【问题讨论】:

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


    【解决方案1】:

    好吧,您可以加载文档一次,将其转换为 Dictionary&lt;int, string&gt;,如下所示:

    var doc = XDocument.Load(HttpContext.Current.Server.MapPath("/App_Data/ErrorCodes.xml"));
    var errors = doc.Root.Elements("error")
                    .ToDictionary(x => (int) x.Attribute("code"),
                                  x => (string) x.Attribute("message"));
    

    (您可以在加载网络应用时执行此操作。)

    或者,如果您真的只需要查找一条消息:

    var doc = XDocument.Load(HttpContext.Current.Server.MapPath("/App_Data/ErrorCodes.xml"));
    var errors = doc.Root.Elements("error")
                    .Where(x => (int) x.Attribute("code") == code)
                    .Single()
                    .Attribute("message").Value;
    

    请注意,XDocument 是 LINQ to XML 的一部分; XmlDocument 不是。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      相关资源
      最近更新 更多