我有一些XML默認命名空間XML的的SelectNodes通過XmlNamespaceManager的默認命名空間無法正常運行
<a xmlns='urn:test.Schema'><b/><b/></a>
,並要計算<b/>
如何做我必須定義
數XmlNamespaceManager nsmgr = ????
Assert.AreEqual(2, doc.SelectNodes("//b", nsmgr).Count);
這樣assert變爲true?
我已經試過到目前爲止(使用NUnit):
[Test]
[Ignore("Why does this not work?")]
public void __DoesNotWork_TestSelectWithDefaultNamespace()
{
// xml to parse with defaultnamespace
string xml = @"<a xmlns='urn:test.Schema'><b/><b/></a>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// fails because xpath does not have the namespace
//!!!!
Assert.AreEqual(2, doc.SelectNodes("//b").Count);
// using XPath defaultnamespace
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("", "urn:test.Schema");
// This will fail with dotnet 3.5sp1. Why?
//!!!!
Assert.AreEqual(2, doc.SelectNodes("//b", nsmgr).Count);
}
[Test]
public void TestSelectWithoutNamespaces_Ok()
{
// xml to parse without namespace
string xml = @"<a><b/><b/></a>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// works ok
Assert.AreEqual(2, doc.SelectNodes("//b").Count);
// works ok
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
Assert.AreEqual(2, doc.SelectNodes("//b", nsmgr).Count);
}
[Test]
public void TestSelectWithNamespacesPrefixed_Ok()
{
// xml to parse with defaultnamespace
string xml = @"<a xmlns='urn:test.Schema'><b/><b/></a>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// using XPath namespace via alias "t". works ok but xpath is to complicated
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("t", doc.DocumentElement.NamespaceURI);
Assert.AreEqual(2, doc.SelectNodes("//t:b", nsmgr).Count);
}
感謝您的回覆。你描述了與第三個Unitest TestSelectWithNamespacesPrefixed_Ok()相同的功能。我仍然希望有一個workaroud,而不需要修改xpath-expression – k3b 2010-11-24 22:03:01