13

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 my question:

I have an xsd file which starts of like this:

Beginning of my xsd file I need to know how to programatically access the namespace value of the above file.

Additionally my solution needs to be generic so I cannot simply search for xmlns:xs because the exact name of the namespace may have a different name

I've tried the following, but when debugging the value of the elementNamespace variable is blank "":

XElement elemet = XElement.Load(@"D:\xsd\Response.xsd");
string elementNamespace = elemet.GetDefaultNamespace().NamespaceName;
System.Diagnostics.Debug.WriteLine("Namespace " + elementNamespace);
1
  • You are missing an 'n' in element. string elementNamespace = element.GetDefaultNamespace().NamespaceName; Commented Sep 20, 2021 at 16:06

3 Answers 3

17

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the link i used the LINQ to XML approach
6

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.

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.