XPath query on XmlNode

C

Claudio

Hi
I'm trying to use XPath queries with streaming XML, but I cannot make
it working.
The solution I'm trying to implement is: create a XmlNode as soon as I
have a full XML element and use the SelectSingleNode method with the
XPath query

Here is a test console application i wrote to better demonstrate my
issue and.. help you help me :)

--------------
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Diagnostics;

class xpath
{
static void Main(string[] args)
{
//INITIALIZATION
//create the xml reader
Stream stream = new MemoryStream(
Encoding.UTF8.GetBytes(
"<iq><bind xmlns='urn:long:namespace'><jid>MYVALUE</jid></bind></iq>")
, false);
XmlReaderSettings xmlRsettings = new XmlReaderSettings();
xmlRsettings.ConformanceLevel = ConformanceLevel.Fragment;
xmlRsettings.IgnoreComments = true;
XmlReader xmlReader = XmlReader.Create(stream, xmlRsettings);

//move to the first element (<iq>)
xmlReader.Read();
XmlDocument doc = new XmlDocument();
//END INITIALIZATION

XmlNode node = doc.ReadNode(xmlReader);

//here I would like to read MYVALUE
//this is OK

Debug.WriteLine(node.ChildNodes[0].ChildNodes[0].ChildNodes[0].Value);
//but I'd rather using a XPath query like
XmlNode val = node.SelectSingleNode("iq/bind/jid/text()");
Debug.WriteLine(val == null ? "null" : val.Value);
}
}
 
M

Martin Honnen

Claudio said:
Stream stream = new MemoryStream(
Encoding.UTF8.GetBytes(
"<iq><bind xmlns='urn:long:namespace'><jid>MYVALUE</jid></bind></iq>")
, false);

The bind element and its child jid element are in the namespace with the
URI urn:long:namespace which means to do XPath on that you nead an
XmlNamespaceManager instance, bind a prefix to the URI, use that prefix
in your XPath expressions and pass the namespace manager as the second
argument of SelectNodes/SelectSingleNode e.g.

XmlNamespaceManager namespaceManager = new
XmlNamespaceManager(doc.NameTable);
namespaceManager.AddNamespace("pf", "urn:long:namespace");
XmlNode val = node.SelectSingleNode("pf:bind/pf:jid/text()",
namespaceManager);


Note that the XPath expression needed to be corrected in your post.
 

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