我有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解析器? –