代码之家  ›  专栏  ›  技术社区  ›  John Lewin

为什么XElement没有GetAttributeValue方法?

  •  13
  • John Lewin  · 技术社区  · 14 年前

    有时我想知道某些API更改的原因。既然谷歌没有帮我解决这个问题,也许StackOverflow可以。为什么微软选择删除 GetAttribute System.Xml 当时的世界 XmlElement.GetAttribute("x") 喜欢 getAttribute XElement SetAttributeValue 但是 GetAttributeValue 没有实现。

    XElement.Attribute("x").Value 属性,但它不是方便和提供效用函数的一种方式( 设置属性值

    2 回复  |  直到 12 年前
        1
  •  16
  •   Necros    14 年前

    您应该得到如下属性值:

    var value = (TYPE) element.Attribute("x");
    

    更新:

    示例:

    var value = (string) element.Attribute("x");
    var value = (int) element.Attribute("x");
    

    请参阅本文: http://www.hanselman.com/blog/ImprovingLINQCodeSmellWithExplicitAndImplicitConversionOperators.aspx . 属性也是如此。

        2
  •  5
  •   Kirk Woll    14 年前

    不确定确切的原因,但是使用C#扩展方法,您可以自己解决问题。

    public static string GetAttributeValue(this XElement element, XName name)
    {
        var attribute = element.Attribute(name);
        return attribute != null ? attribute.Value : null;
    }
    

    允许:

    element.GetAttributeValue("myAttributeName");