C#解析SVG时XPath获取指定节点下首个path子节点问题
问题原因
- 原XPath表达式语法错误:
[.//path][1]属于无效写法,没有指定要匹配的目标节点类型,无法正确定位元素。 - 未处理SVG默认命名空间:你提供的SVG节点声明了默认命名空间
http://www.w3.org/2000/svg,XmlDocument执行XPath查询时,不带命名空间前缀的选择器无法匹配到带默认命名空间的节点,会直接返回null。 - 原代码缺少空值校验:遍历节点时直接取
class、d属性的Value,碰到对应属性不存在的节点会抛出空引用异常。
修正方案
直接替换为以下代码即可正常获取目标path节点的d属性:
doc = new XmlDocument(); doc.Load(SVG_file); // 注册SVG默认命名空间 XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("svg", "http://www.w3.org/2000/svg"); XmlNodeList GList = doc.GetElementsByTagName("g"); foreach (XmlNode item in GList) { // 增加空判断,过滤无class属性的g节点避免报错 if (item.Attributes["class"] != null && item.Attributes["class"].Value == "Pedale") { foreach (XmlNode PedaleItem in item.ChildNodes) { // 跳过空白文本节点、无GUID属性的节点 if (PedaleItem.NodeType != XmlNodeType.Element || PedaleItem.Attributes["GUID"] == null) continue; // 修正XPath:匹配当前节点下任意层级的第一个path节点,传入命名空间管理器 XmlNode PathNode = PedaleItem.SelectSingleNode(".//svg:path[1]", nsmgr); if (PathNode != null && PathNode.Attributes["d"] != null) { string pathD = PathNode.Attributes["d"].Value; // 在此处编写路径值的后续处理逻辑 } } } }
如果你需要更精准匹配id为
freccia的目标path节点,可以把XPath替换为.//svg:path[@id='freccia'][1],不受节点顺序变动影响,稳定性更高。
内容的提问来源于stack exchange,提问作者Riccardo Palma
相关产品推荐
相关产品推荐

