Groups | Blog | Home
all groups > dotnet xml > february 2005 >

dotnet xml : XPath Query problem with Namespace


MAF
2/18/2005 9:28:41 AM
I am triing to query the following xml document. I am loading the xml into
a XML Document and then using XPath to get the EntityDataSet Node

Here is my code

XMLDoc = new System.Xml.XmlDocument();

if (this.m_FileLocation != null && this.m_FileLocation.Length > 0)

XMLDoc.Load(this.m_FileLocation);

else

{

throw new System.IO.FileNotFoundException("File can not be found",
this.m_FileLocation);

}



//Locate Root

System.Xml.XmlNodeList rootList = XMLDoc.SelectNodes("//EntityDataSet");
//This returns nothing



If I remvoe the xmlns attribute of EntityTree I do get the desired note.
What do I need to do to my XPath to make this work properly?


<?xml version="1.0"?>

<EntityTreeCollection ExportDateTime="2/14/2005 4:57:31 PM"
SystemName="testXP" UserName="test" UserID="45">

<EntityTree xmlns="http://acme.com/EntityTree.xsd"
ExportedFromDataModelVersion="4.9.0" EntityCount="7">

<EntityTreeNode Selected="true">

<EntityDataSet>

<Entity EntityID="10128" EntityName="INTLOAD"/>

</EntityDataSet>

</EntityTreeNode>

</EntityTree>

</EntityTreeCollection>

Samu Lang
2/18/2005 5:49:39 PM
Your XPath is looking for a node called EntityDataSet whose namespace uri is
empty, while the node you're searching from is qualified by the namespace
"http://acme.com/EntityTree.xsd".



The easy solution is to select the node by local name:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmreflocalnamefunction.asp
http://www.w3.org/TR/xpath#function-local-name

System.Xml.XmlNodeList rootList = XMLDoc.SelectNodes("//*[local-name() =
'EntityDataSet']");



The serious solution is to use namespace manager:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlxmlnamespacemanagerclasstopic.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemXmlXmlNodeClassSelectNodesTopic2.asp

System.Xml.XmlNamespaceManager Manager = new
System.Xml.XmlNamespaceManager(XMLDoc.NameTable);
Manager.AddNamespace("x", "http://acme.com/EntityTree.xsd");

System.Xml.XmlNodeList rootList = XMLDoc.SelectNodes("//x:EntityDataSet",
Manager);

Martin Honnen
2/18/2005 7:46:08 PM


[quoted text, click to view]

You need to bind a prefix to the default namespace and use the prefix in
the XPath expression, see
<http://www.faqts.com/knowledge_base/view.phtml/aid/34022>


--

Martin Honnen
AddThis Social Bookmark Button