【问题标题】:Regex to get value of a particular attribute?正则表达式获取特定属性的值?
【发布时间】:2012-05-30 12:40:44
【问题描述】:

我在这样的代码隐藏中有一部分 XAML 字符串

string str = "<Button Name = \"btn1\" Foo = \"Bar"\ /><TextBox Name=\"txtbox1\">"

应该是什么正则表达式来查找仅 Name 属性的值。

我想要

btn1
txtbox1

怎么做?

【问题讨论】:

标签: c# regex


【解决方案1】:

而你肯定不想这样做?

string str = "<Button Name = \"btn1\" /><TextBox Name=\"txtbox1\"/>";
var attrs = XElement.Parse("<r>"+str+"</r>").Elements().Attributes("Name").Select(a => a.Value);

foreach (var attr in attrs) Console.WriteLine(attr);

【讨论】:

  • 我正在从 System.Xml.Linq 获取 XElement。如果这是正确的,那么 Elements().Attributes() 说它是一个错误。
  • 您需要在代码中添加using System.Xml.Linq 块,而不是直接访问System.Xml.Linq.XElement,因为Attributes() 是IEnumerable&lt;XElement&gt; 上的扩展方法,需要纳入范围。另请注意,在重新阅读您的问题后,我现在正在使用.Attributes("Name")。
【解决方案2】:

除了 LINQ,您还可以使用 XPath 来获取值。这将为您提供第一个 Button 的名称:

string str = "<Button Name = \"btn1\" /><TextBox Name=\"txtbox1\"/>";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root>" + str + "</root>");
string name = doc.SelectSingleNode("root/Button/@Name").InnerText;

或者,如果您只想获取任何项目的名字属性:

string name = doc.SelectSingleNode("root/*/@Name").InnerText;

或获取所有项目的所有名称属性的列表:

foreach (XmlNode node in doc.SelectNodes("root/*/@Name"))
{
    string name = node.InnerText';
}

等等

【讨论】:

    【解决方案3】:

    如果你可以使用环视,试试这个:

    (?<=\bName\b\s*=\s*")[^"]+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2011-02-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多