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では名前空間を文字列として直接扱うことができないようだ。
基礎知識
- XMLのタグにあるxmlnsというものは、「XML namespace」の略称
- xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"というものを「名前空間宣言」と呼ぶ
- このときの「名前空間」はhttp://schemas.xmlsoap.org/soap/envelope/になる
- このときのsoapを「接頭語」と呼ぶ