Search code examples
c#xmlxpathxml-namespacesxmldocument

What is wrong with my attribute-searching XPath query


I have an XPath query which looks right to me, but isn't returning any results.

The XML document it's being tested against:

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Deployment.Parts>
    <AssemblyPart x:Name="foo" Source="foo.dll" />
  </Deployment.Parts>
</Deployment>

The code:

Xml = new XmlDocument();
Xml.LoadXml(text);
Manager = new XmlNamespaceManager(Xml.NameTable);
//use constants for namespaces to make more readable
Manager.AddNamespace("a", NS_DEPLOYMENT_2007); //use 'a' for default namespace here so xpath is easier
Manager.AddNamespace("x", NS_XAML_2006); 

string xpath="//a:Deployment.Parts/a:AssemblyPart[@a:Source='foo.dll']";
var tmp = Xml.SelectNodes(xpath, Manager);

What is wrong with my XPath query here?


Solution

  • You need to remove the namespace prefix from your attribute:

    string xpath="//a:Deployment.Parts/a:AssemblyPart[@Source='foo.dll']";
    

    You only need to specify the namespace for the attribute if it explicitly has a namespace defined, so when you would want to query the Name attribute, you would have to add it:

    string xpath="//a:Deployment.Parts/a:AssemblyPart[@x:Name='foo']";