Hello --
I'm attempting to get a handle on how to do xpath queries with
System.Xml -- so far the biggest hurdle has been how to deal with a
default namespace. If I use the test xml:
<?xml version="1.0" encoding="utf-8" ?>
<thing xmlns="urn:thing-schema-v1">
<foo>foo thing</foo>
<bar>bar thing</bar>
<baz>baz thing</baz>
</thing>
....everything in the code below fails (as in no nodes are located, when
3 should be). However, if I remove the xmlns declaration from the
<thingroot element everything works fine. What am I doing wrong?
using System;
using System.Collections.Generic;
using System.Text;
namespace XmlTest
{
class Program
{
static void Main(string[] args)
{
const string szXPath = "/thing/*";
const string szFilename = @"..\..\test-wo-xmlns.xml";
System.Xml.XmlReader xmlReader = new
System.Xml.XmlTextReader(System.IO.File.OpenRead(s zFilename));
System.Xml.XmlNamespaceManager xmlNsMgr = new
System.Xml.XmlNamespaceManager(xmlReader.NameTable );
xmlNsMgr.AddNamespace(String.Empty, "urn:thing-schema-v1");
System.Xml.XPath.XPathDocument xpath = new
System.Xml.XPath.XPathDocument(xmlReader);
System.Xml.XPath.XPathNavigator xpathNavi =
xpath.CreateNavigator();
System.Xml.XPath.XPathNodeIterator xpathQuery =
xpathNavi.Select(szXPath);
while(xpathQuery.MoveNext())
{
string szValue = xpathQuery.Current.Value;
System.Console.WriteLine(szValue);
}
System.Xml.XPath.XPathExpression xpathExpr =
xpathNavi.Compile(szXPath);
xpathExpr.SetContext(xmlNsMgr);
xpathQuery = xpathNavi.Select(xpathExpr);
while (xpathQuery.MoveNext())
{
string szValue = xpathQuery.Current.Value;
System.Console.WriteLine(szValue);
}
System.Xml.XmlDocument xmlDoc = new
System.Xml.XmlDocument();
xmlDoc.Load(szFilename);
System.Xml.XmlNamespaceManager xmlNsMgr2 = new
System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
xmlNsMgr2.AddNamespace(String.Empty,
"urn:thing-schema-v1");
System.Xml.XmlNodeList xmlNodes =
xmlDoc.SelectNodes(szXPath);
foreach(System.Xml.XmlNode xmlNode in xmlNodes)
{
string szValue = xmlNode.Value;
System.Console.WriteLine(szValue);
}
}
}
}