我正在寻找类似于 jquery 的东西来在 C# 中生成 dom(我不需要解析)。不幸的是,没有找到一个轻量级的解决方案,所以我创建了这个继承自 System.Xml.Linq.XElement 的简单类。关键特性是您可以像在 javascript 中使用 jquery 一样链接运算符,因此它更加流畅。它功能不全,但可以满足我的需要,如果有兴趣,我可以启动一个 git。
public class DomElement : XElement
{
public DomElement(string name) : base(name)
{
}
public DomElement(string name, string value) : base(name, value)
{
}
public DomElement Css(string style, string value)
{
style = style.Trim();
value = value.Trim();
var existingStyles = new Dictionary<string, string>();
var xstyle = this.Attribute("style");
if (xstyle != null)
{
foreach (var s in xstyle.Value.Split(';'))
{
var keyValue = s.Split(':');
existingStyles.Add(keyValue[0], keyValue.Length < 2 ? null : keyValue[1]);
}
}
if (existingStyles.ContainsKey(style))
{
existingStyles[style] = value;
}
else
{
existingStyles.Add(style, value);
}
var styleString = string.Join(";", existingStyles.Select(s => $"{s.Key}:{s.Value}"));
this.SetAttributeValue("style", styleString);
return this;
}
public DomElement AddClass(string cssClass)
{
var existingClasses = new List<string>();
var xclass = this.Attribute("class");
if (xclass != null)
{
existingClasses.AddRange(xclass.Value.Split());
}
var addNewClasses = cssClass.Split().Where(e => !existingClasses.Contains(e));
existingClasses.AddRange(addNewClasses);
this.SetAttributeValue("class", string.Join(" ", existingClasses));
return this;
}
public DomElement Text(string text)
{
this.Value = text;
return this;
}
public DomElement Append(string text)
{
this.Add(text);
return this;
}
public DomElement Append(DomElement child)
{
this.Add(child);
return this;
}
}
示例:
void Main()
{
var html = new DomElement("html")
.Append(new DomElement("head"))
.Append(new DomElement("body")
.Append(new DomElement("p")
.Append("This paragraph contains")
.Append(new DomElement("b", "bold"))
.Append(" text.")
)
.Append(new DomElement("p").Text("This paragraph has just plain text"))
)
;
html.ToString().Dump();
var table = new DomElement("table").AddClass("table table-sm").AddClass("table-striped")
.Append(new DomElement("thead")
.Append(new DomElement("tr")
.Append(new DomElement("td").Css("padding-left", "15px").Css("color", "red").Css("color", "blue")
.AddClass("from-now")
.Append(new DomElement("div").Text("Hi there"))
.Append(new DomElement("div").Text("Hey there"))
.Append(new DomElement("div", "Yo there"))
)
)
)
;
table.ToString().Dump();
}
以上代码的输出:
<html>
<head />
<body>
<p>This paragraph contains<b>bold</b> text.</p>
<p>This paragraph has just plain text</p>
</body>
</html>
<table class="table table-sm table-striped">
<thead>
<tr>
<td style="padding-left:15px;color:blue" class="from-now">
<div>Hi there</div>
<div>Hey there</div>
<div>Yo there</div>
</td>
</tr>
</thead>
</table>