如何用XPath选择XML子节点?iXF格式下Wire长度获取失败排查
问题排查:无法获取XML中的Length元素值
核心原因
你代码里配置的NS1命名空间和XML文档里的不一致:
- XML文档中NS1的命名空间是:
CATIA/V5/Electrical/1.0 - 代码里添加的NS1命名空间却是:
CATIA/V6/Electrical/1.0
命名空间的版本号从V5写成了V6,导致XPath无法识别NS1前缀对应的元素,自然匹配不到NS1:Wire和NS1:Length节点。
修正方案
把代码中NS1命名空间的URL改成和XML一致的即可,同时建议添加节点空值判断,避免空引用异常:
XmlDocument xlDocument = new XmlDocument(); xlDocument.Load(importFile); XmlNamespaceManager nsManager = new XmlNamespaceManager(xlDocument.NameTable); nsManager.AddNamespace("tns", "IXF_Schema.xsd"); nsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); nsManager.AddNamespace("ixf", "http://www.ixfstd.org/std/ns/core/1.0"); // 修正NS1命名空间URL,和XML保持一致 nsManager.AddNamespace("NS1", "CATIA/V5/Electrical/1.0"); nsManager.AddNamespace("NS2", "http://www.ixfstd.org/std/ns/core/classBehaviors/links/1.0"); //Get all wire objects XmlNodeList wires = xlDocument.SelectNodes("descendant::ixf:object[@xsi:type = \"tns:Wire\"]", nsManager); foreach (XmlNode wire in wires) { string wireName = string.Empty; string wireLength = string.Empty; XmlNode nameNode = wire.SelectSingleNode("./tns:Name", nsManager); if (nameNode != null) { wireName = nameNode.InnerText; } XmlNode lengthNode = wire.SelectSingleNode("./NS1:Wire/NS1:Length", nsManager); if (lengthNode != null) { wireLength = lengthNode.InnerText; } }
额外提示
在处理XML节点时,一定要确保所有命名空间的URL和XML文档中的声明完全一致,哪怕是版本号、路径的细微差异都会导致XPath匹配失败。另外,添加空值判断可以避免因节点缺失引发的运行时异常。
内容的提问来源于stack exchange,提问作者user3785768
相关产品推荐
相关产品推荐

