这是一个如何使用HtmlAgilityPack做到这一点的示例。如果您仍想使用正则表达式,请参阅答案的另一部分。
string html = @"<option foo1='bar1' value=""1"" foo=bar></option>";
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var node = doc.DocumentNode.ChildNodes[0];
//Get all the attributes
var attributes = new List<HtmlAttribute>(node.Attributes);
//Remove all the attributes
node.Attributes.RemoveAll();
//Insert them again
foreach (var attr in attributes) {
//If we found the 'value' atrribute, insert it at the begining
if (attr.Name == "value")
{
node.Attributes.Insert(0, attr);
}
else {
node.Attributes.Add(attr);
}
}
Console.WriteLine(doc.DocumentNode.OuterHtml);
上面的代码将打印:
<option value="1" foo="bar" foo1='bar1'>
那只是一个例子。您可以对 HTML 上的所有节点执行此操作,或者仅将其应用于您需要的节点等。
另一个使用正则表达式的例子。您可能需要进行修改以 100% 满足您的需求。
string regex = @"<([\w]+)\s+(?:(\w+)=[""']?([^\s""']+)[""']?\s*)+>";
string html = @"<option foo=bar value=""1"" foo2='bar2'>...</option>
<option foo=bar value=""1"" foo2='bar2'>...</option>
<option foo=bar value=""1"" foo2='bar2'>...</option>";
//Getting all the matches.
var matches = Regex.Matches(html, regex);
foreach (Match m in matches) {
//This will contain the replaced string
string result = string.Format("<{0}", m.Groups[1].Value);
//Here we will store all the keys
var keys = new List<string>();
//Here we will store all the values
var values = new List<string>();
//For every pair (key, value) matched
for (int i = 0; i < m.Groups[2].Captures.Count; i++) {
//Get the key
var key = m.Groups[2].Captures[i].Value;
//Get the value
var value = m.Groups[3].Captures[i].Value;
//Insert on the list (if key is 'value', insert at the beginning)
if (key == "value") {
keys.Insert(0, key);
values.Insert(0, value);
}
else {
keys.Add(key);
values.Add(value);
}
}
//Concatenate all the (key, value) attributes to the replaced string
for (int i = 0; i < keys.Count; i++) {
result += string.Format(@" {0}=""{1}""", keys[i], values[i]);
}
//Close the tag
result += ">";
Console.WriteLine(result);
}
这将打印:
<option value="1" foo="bar" foo2="bar2">
<option value="1" foo="bar" foo2="bar2">
<option value="1" foo="bar" foo2="bar2">