XPath query with namespace scope

G

Guest

i got a xml file which is using a namespace declaration with no prefix, as
you can see here

----
<?xml version="1.0" encoding="utf-8"?>
<configuration
xmlns="http://www.microsoft.com/schema/EnterpriseInstrumentation/v1/EnterpriseInstrumentation.xsd">
<instrumentedApp name="SimpleInstrumentation" mode="released" />
----

when i use the following xpath expression
"/configuration/instrumentedApp/@name"
in order to get the atributte named "name" of the element named
"instrumentedApp", using the following code

----
XmlReader objXmlReader = new XmlTextReader(objFileStream);
System.Xml.XPath.XPathDocument objXPathDocument = new
XPathDocument(objXmlReader);
System.Xml.XPath.XPathNavigator objXPathNavigator =
objXPathDocument.CreateNavigator();

string result = string.Empty;

XPathNodeIterator objXPathNodeIterator =
objXPathNavigator.Select("/configuration/instrumentedApp/@name");
if (objXPathNodeIterator.MoveNext())
result = objXPathNodeIterator.Current.Value.Trim();
----

it simple does not work, because the i have to indicate the namespace scope
of the element.

¿how can i do that?


thanks
 
D

Derek Harmon

Ricardo Quintanilla said:
i got a xml file which is using a namespace declaration with no prefix, as
you can see here : :
<configuration
xmlns="http://www.microsoft.com/schema/EnterpriseInstrumentation/v1/EnterpriseInstrumentation.xsd"> : :
XPathNodeIterator objXPathNodeIterator =
objXPathNavigator.Select("/configuration/instrumentedApp/@name");

To specify a namespace context you should use the XPathExpression overload
of Select( ) and set the Context on the XPathExpression to an XmlNamespace-
Manager.

XPathExpression objExpr = objXPathNavigator.Compile( "ns1:configuration/ns1:instrumentedApp/@name");
XmlNamespaceManager objNamespaces = new XmlNamespaceManager( new NameTable( ) );
objNamespaces.AddNamespace( "ns1",
"http://www.microsoft.com/schema/EnterpriseInstrumentation/v1/EnterpriseInstrumentation.xsd");
objExpr.SetContext( objNamespaces);
XPathNodeIterator objXPathNodeIterator = objXPathNavigator.Select( objExpr);


Derek Harmon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top