我有XAML字符串的代码隐藏这样正则表达式来获取特定属性的值?
string str = "<Button Name = \"btn1\" Foo = \"Bar"\ /><TextBox Name=\"txtbox1\">"
的部分应该是什么只查找名称的属性值的正则表达式。
我想
btn1
txtbox1
如何?
我有XAML字符串的代码隐藏这样正则表达式来获取特定属性的值?
string str = "<Button Name = \"btn1\" Foo = \"Bar"\ /><TextBox Name=\"txtbox1\">"
的部分应该是什么只查找名称的属性值的正则表达式。
我想
btn1
txtbox1
如何?
,你绝对不希望这样做?
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()就说它有错误。 –
您需要在代码中添加'使用System.Xml.Linq'块,而不是直接访问'System.Xml.Linq.XElement',因为'Attributes()'是'IEnumerable
完美。这就像一个魅力。谢谢。 –
试试这个,如果你可以环视使用:
(?<=\bName\b\s*=\s*")[^"]+
除了LINQ之外,您还可以使用XPath来获取值。这将让你的第一个按钮的名称:
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';
}
等
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-se lf-contained-tags – Lakis
请参阅http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – woz
为什么不使用xml/html解析器? –