Get namespace from xml file C#

后端 未结 3 952
北荒
北荒 2021-02-13 18:30

I\'ve browsed the questions with similar titles but cannot seem to find exactly what I\'m looking for,if anyone spotted a similar question kindly point me to the thread.Here is

相关标签:
3条回答
  • 2021-02-13 18:32

    Here's what I ended up using from the Scott Hanselman article

    public static IDictionary<string, string> GetXmlNamespaces(string sourcePath)
    {
        XDocument y = XDocument.Load(sourcePath);
        XPathNavigator foo = y.CreateNavigator();
        foo.MoveToFollowing(XPathNodeType.Element);
        return foo.GetNamespacesInScope(XmlNamespaceScope.All);
    }
    

    Usually the namespace I want is in the value of the 2nd element of the dictionary which I access like so:

    var namespace = GetXmlNamespaces("myfile.xml").ElementAt(1).Value;
    
    0 讨论(0)
  • 2021-02-13 18:39

    Thats because the default namespace is blank / not specified. I'd guess that you want GetNamespaceOfPrefix:

    string elementNamespace = elemet.GetNamespaceOfPrefix("xs").NamespaceName;
    

    Although that doesn't make a whole lot of sense to be honest - I'm not really sure what you are after.

    0 讨论(0)
  • 2021-02-13 18:44

    Scott Hanselman has an article on how to get the namespaces:

    http://www.hanselman.com/blog/GetNamespacesFromAnXMLDocumentWithXPathDocumentAndLINQToXML.aspx

    0 讨论(0)
提交回复
热议问题