代码之家  ›  专栏  ›  技术社区  ›  Simon Keep

如何从XDocument中获取NameTable?

  •  47
  • Simon Keep  · 技术社区  · 17 年前

    如何从XDocument中获取NameTable?

    它似乎没有XmlDocument所具有的NameTable属性。

    document.XPathSelectElements("//xx:Name", namespaceManager);
    

    它工作得很好,但我必须手动将要使用的命名空间添加到XmlNamespaceManager中,而不是像使用XmlDocument那样从XDocument检索现有的名称表。

    4 回复  |  直到 14 年前
        1
  •  33
  •   Martin Liversage    15 年前

    您需要通过XmlReader推送XML,并使用XmlReader的NameTable属性。

    如果您已经有Xml,并且正在加载到XDocument中,请确保使用XmlReader加载XDocument:-

    XmlReader reader = new XmlTextReader(someStream);
    XDocument doc = XDocument.Load(reader);
    XmlNameTable table = reader.NameTable;
    

    如果您正在使用从零开始构建Xml XDocument 您需要调用XDocument CreateReader 然后让读者消费一些东西。

    一旦使用了阅读器(比如,通过加载另一个XDocument,或者更好:有些什么都不做,只会让阅读器浏览XDocument的内容),您就可以检索NameTable。

        2
  •  29
  •   Matthew McDermott    15 年前

    我是这样做的:

    //Get the data into the XDoc
    XDocument doc = XDocument.Parse(data);
    //Grab the reader
    var reader = doc.CreateReader();
    //Set the root
    var root = doc.Root;
    //Use the reader NameTable
    var namespaceManager = new XmlNamespaceManager(reader.NameTable);
    //Add the GeoRSS NS
    namespaceManager.AddNamespace("georss", "http://www.georss.org/georss");  
    //Do something with it
    Debug.WriteLine(root.XPathSelectElement("//georss:point", namespaceManager).Value);  
    
        3
  •  7
  •   Alex    11 年前

    XmlNamespaceManager,而不是从中检索现有的名称表 XDocument,就像您使用XmlDocument一样。

    XDocument project = XDocument.Load(path);
    //Or: XDocument project = XDocument.Parse(xml);
    var nsMgr = new XmlNamespaceManager(new NameTable());
    //Or: var nsMgr = new XmlNamespaceManager(doc.CreateReader().NameTable);
    nsMgr.AddNamespace("msproj", "http://schemas.microsoft.com/developer/msbuild/2003");
    var itemGroups = project.XPathSelectElements(@"msproj:Project/msproj:ItemGroup", nsMgr).ToList();
    
        4
  •  2
  •   Sylwester Santorowski    6 年前

    它也可以通过XPathNavigator完成。当您既不知道Xml文件编码也不知道命名空间前缀时,它可能很有用。

    XDocument xdoc = XDocument.Load(sourceFileName);
    XPathNavigator navi = xdoc.Root.CreateNavigator();
    XmlNamespaceManager xmlNSM = new XmlNamespaceManager(navi.NameTable);
    //Get all the namespaces from navigator
    IDictionary<string, string> dict = navi.GetNamespacesInScope(XmlNamespaceScope.All);
    //Copy them into Manager
    foreach (KeyValuePair<string, string> pair in dict)
    {
        xmlNSM.AddNamespace(pair.Key, pair.Value);
    }