XPathと名前空間

どうせならSOAPで、とWebサービスプログラミングの実験をしていたら、
C#+.NETでXPath名前空間で大いにはまったので、それに関連するメモを残しておく。

例えば、.NETでWebサービスを作ると以下のようなXMLが取得できる。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
	<soap:Body>
		<TestResponse xmlns="http://tempuri.org/">
			<TestResult>
				<Value>1</Value>
			</TestResult>
		</TestResponse>
	</soap:Body>
</soap:Envelope>

このとき、Valueの値を取るためには、以下のようなコードを書く。

void Parse( string filename )
{
	XmlDocument doc = new XmlDocument();
	doc.Load( filename );

	XmlNamespaceManager nsmgr = new XmlNamespaceManager( doc.NameTable );
	nsmgr.AddNamespace( "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/" );
	//nsmgr.AddNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );
	//nsmgr.AddNamespace( "xsd", "http://www.w3.org/2001/XMLSchema" );
	nsmgr.AddNamespace( "test", "http://tempuri.org/" );

	XmlNode node = doc.SelectSingleNode( "/SOAP-ENV:Envelope/SOAP-ENV:Body/test:TestResponse/test:TestResult/test:Value/text()", nsmgr );
}

XPathでは名前空間を文字列として直接扱うことができないようだ。

基礎知識