を使用してc#.NETで有効なXMLドキュメントを解析しようとしていますxPathNavigator
。XMLドキュメントの開始は次のようになります。
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns1:myResponse xmlns:ns1="ExampleNS" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<myReturn href="#2" />
ご覧のとおり、ルート要素にはいくつかの名前空間が定義されていますが、ns1
後で定義されます。xPathクエリを評価しようとすると、次/soapenv:Envelope/soapenv:Body/ns1:myResponse/myReturn
のようになりますXPathException
。
Namespace prefix 'ns1' is not defined.
私がやっていることは、XMLドキュメントを文字列として取得し、それをXmlDocument
オブジェクトにロードすることです。次に、ナビゲーターを作成し、ルート要素に移動してを呼び出しGetNamespacesInScope(XmlNamespaceScope.All)
ます。、、の名前空間を含むこのコレクションをループしxml
、ルートsoapenv
で定義されているように、それらを名前空間マネージャーに追加しますxsd
。xsi
次に、を作成しxPathNavigator
て呼び出しEvaluate
、例外を取得します。
コードはこれです:
string response = GetXMLString();
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(response);
var xmlDocumentNavigator = xmlDocument.CreateNavigator();
xmlDocumentNavigator.MoveToFollowing(XPathNodeType.Element);
var xnm = new XmlNamespaceManager(xmlDocument.NameTable);
var namespacesInScope = xmlDocumentNavigator.GetNamespacesInScope(XmlNamespaceScope.All);
if (namespacesInScope != null)
{
foreach (var prefix in namespacesInScope.Keys)
{
xnm.AddNamespace(prefix, namespacesInScope[prefix]);
}
}
var xPathDocument = new XPathDocument(new StringReader(response));
var xPathNavigator = xPathDocument.CreateNavigator();
xPathNavigator.Evaluate("/soapenv:Envelope/soapenv:Body/ns1:myResponse/myReturn", xnm);
GetNamespacesInScope
メソッドがうまくいかないのはなぜns1
ですか?