【发布时间】:2020-10-04 23:40:04
【问题描述】:
我有一个如下所示的 .svg 文件:
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="topLevelGroup">
<rect
style="fill:#ff00ff;fill-opacity:1.0;stroke:#000000;stroke-width:1;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rectPurple"
width="60.0"
height="30.0"
x="60.0"
y="90.0" />
<rect
style="fill:#ffffff;fill-opacity:1.0;stroke:#000000;stroke-width:2;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rectWhite"
width="90.0"
height="30.0"
x="30.0"
y="130.0" />
所以“g”是一个组,并且有多个组而不是一个组,每个组都有一个唯一的 id 属性(这里是 topLevelGroup)。我的任务是编写一个获取组 id 作为参数并返回该组中矩形颜色的方法。出于某种原因,我无法收集这些颜色。这是我尝试过的:
private IEnumerable<XElement> Groups => root.Descendants(ns + "g");
internal IEnumerable<string> GetColorsOfRectsInGroup(string id)
{
IEnumerable<XElement> spec_groups = Groups.Where(g => g.Attribute("id").Value.Contains(id))
.Select(g => g);
IEnumerable<string> colors = from r in spec_groups.Descendants("rect")
select r.GetFillColor();
return colors;
}
所以基本上我首先尝试收集与参数 id 匹配的所有组,然后获取后代“rect”对象及其颜色。我没有收到任何错误消息,它根本没有通过测试。这里也是检查这个的测试方法:
public void GetColorsOfRectsInGroup()
{
var colors = s1.GetColorsOfRectsInGroup("group1");
Assert.True(UnorderedCompareSequences<string>(new string[] { "#ff0000", "#ffff00" },
colors));
colors = s2.GetColorsOfRectsInGroup("group2");
Assert.True(UnorderedCompareSequences<string>(new string[] { "#00ff00", "#0000ff" },
colors));
}
我今天刚开始使用 Linq,我一直在浏览网站,但我无法弄清楚。我做错了什么?
【问题讨论】:
-
您缺少
Descendants("rect")的命名空间,应该是Descendants(ns + "rect")