【发布时间】:2016-04-02 03:58:43
【问题描述】:
我想使用 Linq 访问 SVG styling properties。对于像椭圆这样的 SVG 元素,我可以简单地检查它们的属性并获取相应的值。假设我的 svg 文件包含这个椭圆:
<ellipse
style="fill:#ff0000;fill-rule:evenodd;stroke:#ff60ff;stroke-width:0.47105053px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="path3338"
cx="457.0145"
cy="261.14557"
rx="102.28526"
ry="126.51072"
transform="matrix(0.79195929,0.6105739,-0.6105739,0.79195929,0,0)" />
我使用此代码获取信息:
XDocument xml = XDocument.Load(PathToSvgFile);
IEnumerable<XElement> xmlEllipses = xml.Descendants("{http://www.w3.org/2000/svg}ellipse");
SvgEllipse[] ellipses = (
from data in xmlEllipses
select new SvgEllipse
{
Cx = data.Attribute("cx") != null
? (double)data.Attribute("cx")
: 0,
Cy = data.Attribute("cy") != null
? (double)data.Attribute("cy")
: 0,
Rx = data.Attribute("rx") != null
? (double)data.Attribute("rx")
: 0,
Ry = data.Attribute("ry") != null
? (double)data.Attribute("ry")
: 0
}
).ToArray();
这段代码从给定的 svg 文件中选择所有椭圆元素并将其属性保存在我的椭圆类中。
我想对每个元素的样式属性做同样的事情。问题是,style 属性的value 是整个样式字符串:
fill:#ff0000;fill-rule:evenodd;stroke:#ff60ff;stroke-width:0.47105053px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1
目前我正在处理该字符串,使用string.Split() 和string.StartsWith() 函数来查找正确的属性及其值。它有效,但我认为它不安全且难以阅读。与本主题类似 (Parse style attribute collection using linq)。
是否有可能以简单的方式处理样式属性,如上所示?
我希望我的问题很清楚。提前致谢!
A.初学者
【问题讨论】:
-
你需要一个 CSS 解析器。这是我在搜索这样的东西时发现的第一个。 github.com/Athari/CsCss
-
你看到我的回答了吗?
-
@Alberto 是的,我看到了您的回答,看起来很有希望!虽然我没有时间测试它。但是,如果它对我有用,我现在会这样做并将其标记为正确答案。 :) 这比我的方法更安全,但仍然有一些字符串拆分。但我想像椭圆示例这样的查询没有办法做到这一点。