473,549 Members | 2,701 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XmlDocument.Sel ectSingleNode XPathException

Hi;

I am calling SelectSingleNod e("/xml/s:Schema/s:ElementType/@name") where
"/xml/s:Schema/s:ElementType/@name is a legit xpath statement (xml is the
name of the rootnode) and that xpath statement works fine on the document in
XmlSpy.

However, when I call this is .NET 1.1, I get the following exception:

XPathException {"Namespace Manager or XsltContext needed. This query has a
prefix, variable, or user-defined function."}

Any ideas?
--
thanks - dave
Nov 12 '05 #1
6 7793
Hi Dave,

Welcome to MSDN newsgroup.
As for the XPathException you encountered, it is caused by the namespace
prefix in the xpath didn't has a namespace URI mapped. In .net , when we
call xpath selection API and the xpath expression contains namespace
prefix, we need to attach an XmlNamespaceMan ager which contains the
namespace mapping (prefix <---> actual URI). The following MSDN reference
have mentioned using XmlNamespaceMan ager in both XmlNode.SelectS ingleNode
or through XPathNavigator:

#XPath Queries with Namespaced Mapped Prefixes
http://msdn.microsoft.com/library/en...hquerieswithna
mespacedmappedp refixes.asp?fra me=true

#XmlNode.Select SingleNode Method
http://msdn.microsoft.com/library/en...XmlXmlNodeClas
sSelectSingleNo deTopic.asp?fra me=true

Hope helps. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 12 '05 #2
Hi;

Since I don't know the namespaces beforehand I need to read them from the
xml file. Is there any way to tell .NET to read them itself (they are in the
file)? If not, is there a method call to get the set of defined namespaces so
I can then set them?

thanks - dave
"Steven Cheng[MSFT]" wrote:
Hi Dave,

Welcome to MSDN newsgroup.
As for the XPathException you encountered, it is caused by the namespace
prefix in the xpath didn't has a namespace URI mapped. In .net , when we
call xpath selection API and the xpath expression contains namespace
prefix, we need to attach an XmlNamespaceMan ager which contains the
namespace mapping (prefix <---> actual URI). The following MSDN reference
have mentioned using XmlNamespaceMan ager in both XmlNode.SelectS ingleNode
or through XPathNavigator:

#XPath Queries with Namespaced Mapped Prefixes
http://msdn.microsoft.com/library/en...hquerieswithna
mespacedmappedp refixes.asp?fra me=true

#XmlNode.Select SingleNode Method
http://msdn.microsoft.com/library/en...XmlXmlNodeClas
sSelectSingleNo deTopic.asp?fra me=true

Hope helps. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 12 '05 #3

Thanks for your reply Dave,

As far as I known, the XmlDocument or XmlNode hasn't as certain method to
retrieve all the namepace/prefix pairs in itself or sub nodes. Generally if
the xpath is passed from other components, they should also provide the
namespace/prefix pair which are necessary. If you want to programmaticaly
retreive all the namespace/prefix pairs in a XmlDocument( in memory or from
file). We can use XmlTextReader to loop through all the nodes in the xml
document and retrieve all the namespaces/prefix pairs in xml document like;

XmlTextReader reader = new XmlTextReader(@ "..\..\data.xml ");

XmlNamespaceMan ager nsmanager = new XmlNamespaceMan ager(doc.NameTa ble);

while (reader.Read())
{
nsmanager.AddNa mespace(reader. Prefix, reader.Namespac eURI);
}

reader.Close();

Then, we can loop through all the namepspace through:

foreach (String prefix in nsmanager)
{
Console.WriteLi ne("Prefix={0} , Namespace={1}",
prefix,nsmgr.Lo okupNamespace(p refix));
}
However, this nsmanager can be used only for those full qualified element
in xpath. For example, if a xmldocument has a default namespace, we need to
explicitly specify an prefix for it in XmlNamespaceMan ger rather than add
it as default namespace:

=============== ==============
<root xmlns="http://www.test.org"
xmlns:sns="http ://www.test.org/sub"
xmlns:mns="http ://www.test.org/mini">
<data>
<items>
<item id="1">
<sns:subItem sid="11">

</sns:subItem>
<sns:subItem sid="12">

</sns:subItem>
</item>
<item id="2">
<sns:subItem sid="21">

</sns:subItem>
</item>
</items>
</data>
</root>
=============== =============== ========

XmlNamespaceMan ager mgr = new XmlNamespaceMan ager(new NameTable());
mgr.AddNamespac e("tns", "http://www.test.org");
mgr.AddNamespac e("sns","http ://www.test.org/sub");

XmlDocument doc = new XmlDocument();

doc.Load(@"..\. .\data.xml");
string xpath = "//tns:data/tns:items/tns:item/sns:subItem";
XmlNode node = doc.SelectSingl eNode(xpath,mgr );

Console.WriteLi ne("{0}", node==null);

#Use mgr.AddNamespac e(string.Empty, "http://www.test.org")
and xpath = "//data/items/item/sns:subItem" will not work.
HTH. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 12 '05 #4
Yuck.

Our situation is users will pass an xml file to our application so we have
no way of knowing what namespaces they are using. And it would be really bad
if we asked them to type in namespaces that are in the file. So I guess we'll
have to parse.

It's strange that .NET requires that the namespaces be set when they exist
in the xml itself. I work in java too and every java library that implements
xpath reads the namespaces itself from the xml.

Are you sure .NET has this limitation?

thanks - dave

"Steven Cheng[MSFT]" wrote:

Thanks for your reply Dave,

As far as I known, the XmlDocument or XmlNode hasn't as certain method to
retrieve all the namepace/prefix pairs in itself or sub nodes. Generally if
the xpath is passed from other components, they should also provide the
namespace/prefix pair which are necessary. If you want to programmaticaly
retreive all the namespace/prefix pairs in a XmlDocument( in memory or from
file). We can use XmlTextReader to loop through all the nodes in the xml
document and retrieve all the namespaces/prefix pairs in xml document like;

XmlTextReader reader = new XmlTextReader(@ "..\..\data.xml ");

XmlNamespaceMan ager nsmanager = new XmlNamespaceMan ager(doc.NameTa ble);

while (reader.Read())
{
nsmanager.AddNa mespace(reader. Prefix, reader.Namespac eURI);
}

reader.Close();

Then, we can loop through all the namepspace through:

foreach (String prefix in nsmanager)
{
Console.WriteLi ne("Prefix={0} , Namespace={1}",
prefix,nsmgr.Lo okupNamespace(p refix));
}
However, this nsmanager can be used only for those full qualified element
in xpath. For example, if a xmldocument has a default namespace, we need to
explicitly specify an prefix for it in XmlNamespaceMan ger rather than add
it as default namespace:

=============== ==============
<root xmlns="http://www.test.org"
xmlns:sns="http ://www.test.org/sub"
xmlns:mns="http ://www.test.org/mini">
<data>
<items>
<item id="1">
<sns:subItem sid="11">

</sns:subItem>
<sns:subItem sid="12">

</sns:subItem>
</item>
<item id="2">
<sns:subItem sid="21">

</sns:subItem>
</item>
</items>
</data>
</root>
=============== =============== ========

XmlNamespaceMan ager mgr = new XmlNamespaceMan ager(new NameTable());
mgr.AddNamespac e("tns", "http://www.test.org");
mgr.AddNamespac e("sns","http ://www.test.org/sub");

XmlDocument doc = new XmlDocument();

doc.Load(@"..\. .\data.xml");
string xpath = "//tns:data/tns:items/tns:item/sns:subItem";
XmlNode node = doc.SelectSingl eNode(xpath,mgr );

Console.WriteLi ne("{0}", node==null);

#Use mgr.AddNamespac e(string.Empty, "http://www.test.org")
and xpath = "//data/items/item/sns:subItem" will not work.
HTH. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 12 '05 #5
Hi Dave,

Thanks for your followup.
As for using XmlNamespaceMan ager to help executing XPATH in xmldocument
which contains namespace/prefix, I don't think it's the limitation of
net's XML interfaces. I'm sure this is a quite reasonable feature, here is
the reason why the XmlNamespaceMan ager is necessary:

When there is namespace in an xml document to scope elements in different
area(schemas), we use prefixs to identify namespaceURI. Like:

=============== =============== =
<?xml version="1.0" encoding="utf-8" ?>
<root xmlns="http://www.test.org"
xmlns:sns="http ://www.test.org/sub">
<data>
<items>
<item id="1">
<sns:subItem sid="11">

</sns:subItem>
<sns:subItem sid="12">

</sns:subItem>
</item>
</items>
</data>
</root>
=============== ===============

when we need to quer the <sns:subItem sid="11">

maybe we'll think that use the following xpath is quite normal:

//sns:subItem[@sid="11"]

However, according to the W3C XPATH1.0 specification. The full qualified
name of an element is actually it's namespaceURI(no t prefix) combined with
its localname, that means the above path should be:

//http://www.test.org/sub:subItem[@sid="11"]

And as we known, namespace prefix is just a alias of namespaceURI, which
can be replaced by any other one as long as it can uniquely identity that
namespaceURI in the document. So .net framework provide the
XmlNamespaceMan ager which can help specify Namespace with arbitary prefix
value. For example, the above selection can be replaced by

XmlNamespaceMan ager mgr = new XmlNamespaceMan ager(new NameTable());

mgr.AddNamespac e("aaa","http ://www.test.org/sub");

string xpath = "//aaa:subItem[@sid='11']";

"sns" is just an alias, the actual idenitfy is "http://www.test.org/sub",
and the prefix in xpath should be able to be replaced by another alias.
(not only limited to "sns")

I'm not sure if those JAVA xml api is capable of this. However, at least I
think using prefix directly in xpath without any mapping info between
prefix---namespaceURI is not a reasonable behavior. Also, some times we're
not executing Xpath on a whole XmlDocument, just on a XmlNode , then where
does the API to look for the namespace /prefix declaration on the fly?
That's also why the .net using the XmlNamespaceMan ager to specify the
prefix---namespaceURI mapping.

#HOW TO: Specify Namespaces When You Use an XmlDocument to Execute XPath
Queries in Visual C# .NET
http://support.microsoft.com/default...b;en-us;318545

If you still have anything unclear, please feel free to post here. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Nov 12 '05 #6
Thanks for your reply Dave,

As you said:
===========
The "xmlns:sns="htt p://www.test.org/sub">" in the xml itself provides the
necessary information to turn:
//sns:subItem[@sid="11"]
into:
//http://www.test.org/sub:subItem[@sid="11"]
===========

yes, the XML Node or fragment did include the namespace declaraion.
However, this doesn't means that our XPATH can only use "sns" to idenity
the "http://www.test.org/sub" namespace. The "sns" is only an alias. So
the following two xml fragment should be identical (validate through schema)

#fragment A
<root xmlns:sns="http ://www.test.org/sub">
<sns:item>
.......
</sns:item>
</root>

#fragment B
<root xmlns:aaa="http ://www.test.org/sub">
<aaa:item>
.......
</aaa:item>
</root>

However, if we only use the

"//sns:item" xpath and haven't specify an prefix/ URI mapping, it
will only work( using the JAVA API you mentioned) in

fragment A , but not in fragment B( though framgment A is exactly the same
xml document as fragment B).

And when using .net's Xpath selection, since we specify the
XmlNamespaceMan ager which provide the prefix(in our xpath) ----
namespaceURI mapping , we can perform the xpath selection no matter the
namespace prefix is changed to anyone in the source xml document. Also,
the prefix in our XPATH can vary , such as :

//bbb:item using AddNamespace("b bb", "http://test.org/sub")

//ccc:item using AddNamespace("c cc", "http://test.org/sub")

Anyway, I think the prefix( in xpath ) is not simply an alias( it should
always has a namespaceURI mapped to it) , otherwise, the prefix will be
meaningless alone.

Just some of my understanding. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)



Nov 12 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6194
by: Dave | last post by:
Hi, Is there an easier way to pull a subset of nodes from one XmlDocument to another? I have the code below but would like to know if there is a more streamlined method. Thanks, Dave XmlNodeList nodeList = doc1.SelectNodes("//row"); foreach (XmlNode nodeCode in nodeList) { sb.Append(nodeCode.OuterXml);
3
1663
by: Marco Rizzi | last post by:
Hi all, i'm trying to add same node to XmlDocument. This is Xml that I want to create: <TableColumns> <TableColumn><Width>1.5in</Width></TableColumn> <TableColumn><Width>1.5in</Width></TableColumn> <TableColumn><Width>1.5in</Width></TableColumn> <TableColumn><Width>1.5in</Width></TableColumn> </TableColumns>
19
16105
by: David Thielen | last post by:
Hi; If there are no namespaces this works fine for me. But if the xml has namespaces, then I get either no node back or an exception. Here is the sample xml: <root xmlns="http://www.test.org" xmlns:sns="http://www.test.org/sub" xmlns:mns="http://www.test.org/mini"> <data>
4
18167
by: Jesper Stocholm | last post by:
I have a database class that maintains data about customers i my system. The basic XML for this looks like: <Chunk> <Vendor> <Database/> </Vendor> </Chunk> When a user is to be registrered in the system, XML like this is created
5
7915
by: Gnic | last post by:
Hi , I have an XmlDocument instance, I want to find a node in the xml, but I don't know it's path until runtime, for example <aaa> <bbb name="x"/> <aaa attr="y"> <ccc>sometext</ccc> </aaa>
0
2009
by: Ewan Fairweather | last post by:
Hi, I'm generating the below XML in c# for an asp.net application When i've generated this XML the <LaboratoryDetails xmlns=""> element has a blank xmlns set. How do i either a) remove this attribute or b) prevent it from happening in the first place. To generate the xml I've got two template files which i've included at the bottom...
4
4527
by: Daniel | last post by:
Is it possible to use regular expressions inside of an xpath statement executed by System.Xml.XmlDocument.SelectSingleNode() ? string sdoc = "<foo><bar a='1'/><bar a='2'/></foo>"; System.Xml.XmlDocument pdoc = new System.Xml.XmlDocument(); pdoc.LoadXml(sdoc); System.Xml.XmlNode pnode = pdoc.SelectSingleNode("//foo/bar/matches(.,'\\d')");...
5
2323
by: Alan Silver | last post by:
Hello, Sorry if this is an obvious question, but I'm not very familiar with using XmlDocument, and I am struggling with a really simple task. I couldn't find anything clear that explained what I want to do. Suppose I have an XmlDocument like this... <books> <number>3</number>
1
1695
by: =?Utf-8?B?RGF2aWRHQg==?= | last post by:
OK, so I've created and loaded an XMLDocument object. But how do I go about using it? Specifically, how do I: 1) move to the first node (I assume I start on it when I load the XML?) 2) move to the next node (.read?) 3) move back to a previous node? Is there a sample program somewhere to show this? (preferably VB.net) TIA David
0
7720
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7957
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7809
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5088
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1941
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1059
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.