默认命名空间具有不同的性质。默认名称空间声明的元素及其所有后代(没有不同的名称空间声明)在同一默认名称空间中考虑。因此,您也需要为所有后代使用前缀。这个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
它本身已经代表
<ServiceConfiguration>
元素,因此不需要在XPath中包含“ServiceConfiguration”:
/prefix:Role/prefix:ConfigurationSettings/prefix:Setting[1]
..或使用
XDocument
而不是
X元素
如果希望使用与for相同的XPath
XmlDocument
.