使用 XmlNamespaceManager 从 XmlNode 中选择

3

我已经寻找很久了,试图找到一种从具有多个命名空间的XmlNode(而不是XmlDocument)中选择节点的方法。

几乎每篇帖子都建议我使用XmlNamespaceManager,然而,XmlNamespaceManager需要一个XmlNameTable,而XmlNode并没有这个属性。

我尝试过在XmlDocument中进行此操作,因为XmlDocument有一个XmlDocument.NameTable属性,但在XmlNode中不存在。

我尝试手动创建一个NameTable,但它不起作用,因为当我使用XmlDocument时,同样的代码可以正常工作。我猜想我需要用什么东西填充那个NameTable,或者以某种方式将其绑定到XmlNode上才能使其正常工作。请提供建议。

2个回答

4
你能使用什么?
XPathNavigator nav = XmlNode.CreateNavigator();
XmlNamespaceManager man = new XmlNamespaceManager(nav.NameTable);

包含其余内容以便有所帮助:
man.AddNamespace("app", "http://www.w3.org/2007/app"); //Gotta add each namespace
XPathNodeIterator nodeIter = nav.Select(xPathSearchString, man);

while (nodeIter.MoveNext())
{
    var value = nodeIter.Current.Value;
}

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.createnavigator.aspx


0
由于某些原因,XmlNamespaceManager在文档中不会自动加载定义的命名空间(这似乎是一个简单的期望)。由于某种原因,命名空间声明被视为属性。我能够使用以下代码自动添加命名空间。
private static XmlNamespaceManager AddNamespaces(XmlDocument xmlDoc)
{
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
    AddNamespaces(xmlDoc.ChildNodes, nsmgr);
    return nsmgr;
}
private static void AddNamespaces(XmlNodeList nodes, XmlNamespaceManager nsmgr) {
    if (nodes == null)
        throw new ArgumentException("XmlNodeList is null");

    if (nsmgr == null)
        throw new ArgumentException("XmlNamespaceManager is null");

    foreach (XmlNode node in nodes)
    {
        if (node.NodeType == XmlNodeType.Element)
        {
            foreach (XmlAttribute attr in node.Attributes)
            {
                if (attr.Name.StartsWith("xmlns:"))
                {
                    String ns = attr.Name.Replace("xmlns:", "");
                    nsmgr.AddNamespace(ns, attr.Value);
                }
            }
            if (node.HasChildNodes)
            {
                nsmgr.PushScope();
                AddNamespaces(node.ChildNodes, nsmgr);
                nsmgr.PopScope();
            }
        }
    }
}

示例调用:

    XmlDocument ResponseXmlDoc = new System.Xml.XmlDocument();
    ...<Load your XML Document>...
    XmlNamespaceManager nsmgr = AddNamespaces(ResponseXmlDoc);

并使用返回的NamespaceManager

XmlNodeList list = ResponseXmlDoc.SelectNodes("//d:response", nsmgr);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接