加载svg资源时,svg采用xml格式组织数据,在xml node中带有 xmlns,xmlns:xlink两个属性,使用通过的解析方式解析失败,经测试需要在SelectSingleNode/SelectNodes携带namespace查询节点。
xml文档数据如下:
<?xml version="1.0" encoding="UTF-8"?>
<svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 60 (88103) - https://sketch.com -->
<title>设备</title>
<desc>Created with Sketch.</desc>
<defs>
<path d="M6.5,5 L17.5,5 L17.5,19 L6.5,19 L6.5,5 Z M16.5,12 L16.5,10 L15.5,10 L15.5,12 L16.5,12 Z M5.57142857,3 L18.4285714,3 C19.02,3 19.5,3.47435294 19.5,4.05882353 L19.5,19.9411765 C19.5,20.5256471 19.02,21 18.4285714,21 L5.57142857,21 C4.98,21 4.5,20.5256471 4.5,19.9411765 L4.5,4.05882353 C4.5,3.47435294 4.98,3 5.57142857,3 Z M5.5,4 L5.5,20 L18.5,20 L18.5,4 L5.5,4 Z" id="path-1"></path>
<filter x="-60.0%" y="-50.0%" width="220.0%" height="200.0%" filterUnits="objectBoundingBox" id="filter-2">
<feOffset dx="2" dy="2" in="SourceAlpha" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="2" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feColorMatrix values="0 0 0 0 0.436867379 0 0 0 0 0.577989556 0 0 0 0 0.749790468 0 0 0 0.6 0" type="matrix" in="shadowBlurOuter1" result="shadowMatrixOuter1"></feColorMatrix>
<feOffset dx="-2" dy="-2" in="SourceAlpha" result="shadowOffsetOuter2"></feOffset>
<feGaussianBlur stdDeviation="2" in="shadowOffsetOuter2" result="shadowBlurOuter2"></feGaussianBlur>
<feColorMatrix values="0 0 0 0 0.435294118 0 0 0 0 0.576470588 0 0 0 0 0.749019608 0 0 0 0.6 0" type="matrix" in="shadowBlurOuter2" result="shadowMatrixOuter2"></feColorMatrix>
<feMerge>
<feMergeNode in="shadowMatrixOuter1"></feMergeNode>
<feMergeNode in="shadowMatrixOuter2"></feMergeNode>
</feMerge>
</filter>
</defs>
<g id="设备" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="矩形">
<rect x="0" y="0" width="24" height="24"></rect>
<g id="形状" fill-rule="nonzero">
<use fill="black" fill-opacity="1" filter="url(#filter-2)" xlink:href="#path-1"></use>
<use fill="#FFFFFF" xlink:href="#path-1"></use>
</g>
</g>
</g>
</svg>
正确解析代码如下:此时能获取到path节点。
XmlDocument doc = new XmlDocument();
XmlReaderSettings setting = new XmlReaderSettings();
setting.IgnoreComments = true;
XmlReader reader = XmlReader.Create(strPath, setting);
doc.Load(reader);
reader.Close();
XmlNamespaceManager xns = new XmlNamespaceManager(doc.NameTable);
xns.AddNamespace("ns", "http://www.w3.org/2000/svg");
xns.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
//读xml
XmlNode node = doc.SelectSingleNode("ns:svg/ns:defs/ns:path", xns);
if (node != null)
{
...
}
当使用如下代码访问时,查询失败,返回null
XmlDocument doc = new XmlDocument();
XmlReaderSettings setting = new XmlReaderSettings();
setting.IgnoreComments = true;
XmlReader reader = XmlReader.Create(strPath, setting);
doc.Load(reader);
reader.Close();
//读xml
XmlNode node = doc.SelectSingleNode("svg/defs/path");
if (node != null)
{
...
}