通过XmlNamespaceManager使用默认命名空间的Xml-SelectNodes

我有一些带有默认名称空间的xml


<a xmlns='urn:test.Schema'><b/><b/></a>

并想数 <b/>


我该如何定义


XmlNamespaceManager nsmgr = ????

Assert.AreEqual(2, doc.SelectNodes("//b", nsmgr).Count);

这样断言变为事实?


到目前为止,我已经尝试过(使用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);

}


富国沪深
浏览 1439回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP