将XPath与XML命名空间一起使用
我想用XPath处理下面的xml:
Tere是根元素的xmlns
。
我的代码是这样的:
XElement doc = XElement.Load(xmlFilePath); XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable()); ns.AddNamespace("prefix", "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"); XElement settingDiagConnectionString = doc.XPathSelectElement("//prefix:ServiceConfiguration/Role/ConfigurationSettings/Setting[1]", ns); // <===== always return null. settingDiagConnectionString.SetAttributeValue("value", "hello, world!");
但是settingDiagConnectionString
始终为null。
为什么?
加1
谢谢har07。
为每个元素添加前缀后,以下代码有效:
XmlDocument doc = new XmlDocument(); doc.Load(cscfgPath); XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable()); ns.AddNamespace("prefix", "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"); XmlNode settingDiagConnectionString = doc.SelectNodes("/prefix:ServiceConfiguration/prefix:Role/prefix:ConfigurationSettings/prefix:Setting[1]", ns)[0]; settingDiagConnectionString.Attributes["value"].Value = "hello,world!";
但是下面的代码仍然不起作用。 settingDiagConnectionString
仍为null。 为什么?
XElement doc = XElement.Load(cscfgPath); XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable()); ns.AddNamespace("prefix", "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"); XElement settingDiagConnectionString = doc.XPathSelectElement("/prefix:ServiceConfiguration/prefix:Role/prefix:ConfigurationSettings/prefix:Setting[1]", ns); settingDiagConnectionString.SetAttributeValue("value", "hello, world!");
默认名称空间有不同的性质 默认命名空间声明的元素及其所有后代,没有在同一默认命名空间中考虑不同的命名空间声明。 因此,您还需要为所有后代使用前缀。 这个XPath对我很好:
XElement doc = XElement.Parse(xml); XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable()); ns.AddNamespace("prefix", "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"); XElement settingDiagConnectionString = doc.XPathSelectElement("//prefix:Role/prefix:ConfigurationSettings/prefix:Setting[1]", ns); settingDiagConnectionString.SetAttributeValue("value", "hello, world!");
更新:
回应您的更新。 那是因为你正在使用XElement
。 在这种情况下, doc
it self已经代表
元素,因此您不需要在XPath中包含“ServiceConfiguration”:
/prefix:Role/prefix:ConfigurationSettings/prefix:Setting[1]
..或者如果你想使用与XmlDocument
相同的XPath使它运行,则使用XDocument
而不是XElement
。