如何列出XML中的所有名称空间? [英] how i can list out all the namespace in XML?

查看:94
本文介绍了如何列出XML中的所有名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本要求是从XML文件中获取元素值,我已经使用XMLDoxument.SelectSingleNode.我的XML文件的标头中包含一些命名空间,因此我使用了NameSpaceManager来添加命名空间前缀,并且使用了前缀来获取该特定元素.现在,在我的XML文件中,名称空间正在变化,我不想做任何硬编码,有什么方法可以找出所有名称空间并将其添加到NameSpaceManager.

My basic requirement is to get element value from the XML file, i have used XMLDoxument.SelectSingleNode. My XML file contains some Namespace in header, so i have used NameSpaceManager to add namespace-prefix and i have used prefix to get that particular element. Now in my XML files that namespaces are getting vary, i don’t want to do any hard coding, is there any way that i can find out all the namespaces and i can add it to NameSpaceManager.

谢谢.

推荐答案

命名空间可以在xml文档中的任何位置找到.因此,要提取所有名称空间并将其声明到XmlNamespaceManager中,我执行了以下操作:

Namespaces can be found anywhere inside xml document. So to extract all namespaces and declare them into a XmlNamespaceManager I did the following:

public static XmlNamespaceManager getAllNamespaces(XmlDocument xDoc)
{
    XmlNamespaceManager result = new XmlNamespaceManager(xDoc.NameTable);

    IDictionary<string, string> localNamespaces = null;
    XPathNavigator xNav = xDoc.CreateNavigator();
    while (xNav.MoveToFollowing(XPathNodeType.Element))
    {
        localNamespaces = xNav.GetNamespacesInScope(XmlNamespaceScope.Local);
        foreach (var localNamespace in localNamespaces)
        {
            string prefix = localNamespace.Key;
            if (string.IsNullOrEmpty(prefix))
                    prefix = "DEFAULT";

            result.AddNamespace(prefix, localNamespace.Value);
        }
    }

    return result;
}

只需注意默认名称空间的情况.我将默认名称空间重新定义为"DEFAULT"前缀,因为在查询默认名称空间时使用上面返回的名称空间管理器进行SelectSingleNode时遇到问题.我是我的解决方法. 希望对您有帮助

Just pay attention to the default namespace case. I redefined default namespace as "DEFAULT" prefix because I had problems when making SelectSingleNode using the above returned namespace manager when querying the default namespace. I was my workaround. Hope this helps

这篇关于如何列出XML中的所有名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆