【问题标题】:XPath select node with mixture of default and non-default namespace混合了默认和非默认命名空间的 XPath 选择节点
【发布时间】:2018-01-05 12:00:15
【问题描述】:

我有一些 xml,我想使用 xpath(使用 C#)选择密码节点

<?xml version='1.0' encoding='utf-16'?>
<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>
    <s:Body>
        <Search xmlns='https://temp.org'>
            <context>
                <Password>MyS3cretP@ssword</Password>
                <UserID>MyUserId</UserID>
            </context>
        </Search>
    </s:Body>
</s:Envelope>

下面的代码没有找到节点,不知道为什么。我认为这与一些具有定义命名空间的 xml 和一些使用默认命名空间有关。

var doc = new XmlDocument();
doc.LoadXml(request);
var nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");

var node = doc.SelectSingleNode("/s:Envelope/s:Body/Search/context/Password", nsmgr);

在不更改 xml 内容的情况下如何选择 Password 节点?

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    它没有找到节点,因为 Search 节点及其中的所有内容都在 https://temp.org 命名空间中。您需要在命名空间管理器和 XPath 中考虑到这一点:

    var doc = new XmlDocument();
    doc.LoadXml(request);
    var nsMgr = new XmlNamespaceManager(doc.NameTable);
    nsMgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
    nsMgr.AddNamespace("t", "https://temp.org");
    
    var node = doc.SelectSingleNode("/s:Envelope/s:Body/t:Search/t:context/t:Password", nsMgr);
    

    【讨论】:

    • 完美,谢谢。一位同事只是同样的事情,现在一切都按预期工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2010-10-07
    • 2011-08-31
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多