Note that there are some explanatory texts on larger screens.

plurals
  1. POSimplest way to get a URI from an attribute value?
    primarykey
    data
    text
    <p>In my XML, I have an element like</p> <pre><code>&lt;myElement myAttribute="myNamespacePrefix:foobar"/&gt; </code></pre> <p>There is a xmlns declaration in this file:</p> <pre><code>&lt;xmlns:myNamespacePrefix="http://www.mydomain.com/blah#"/&gt; </code></pre> <p>I want to make a URI from the value of myAttribute.</p> <p>IE, I want:</p> <pre><code>http://www.mydomain.com/blah#foobar </code></pre> <p>Sounds simple, doesn't it?</p> <p>So what is the simple solution?</p> <p>I couldn't find anything in the Framework or on MSDN, so I just had to write this no-doubt bug-ridden mess:</p> <pre><code>public static Uri GetUri(string value, XElement containingElement) { if (value.Contains(":")) { var prefix = String.Concat(value.TakeWhile(c =&gt; c != ':')); XNamespace ns; if (containingElement.GetNamespaceOfPrefix(prefix) != null) ns = containingElement.GetNamespaceOfPrefix(prefix); else ns = containingElement.GetDefaultNamespace(); var localName = String.Concat(value.SkipWhile(c =&gt; c != ':').Skip(1)); Contract.Assert(ns != null); if (String.IsNullOrWhiteSpace(ns.NamespaceName)) return new Uri(value); else { StringBuilder sb = new StringBuilder(ns.NamespaceName); if (!ns.NamespaceName.EndsWith("#")) { sb.Append('#'); } return new Uri(String.Format(CultureInfo.CurrentCulture, "{0}{1}", sb.ToString(), localName)); } } else // no namespace prefix { String fragment; if (!value.StartsWith("#")) fragment = value.Insert(0, "#"); else fragment = value; var uriString = String.Format(CultureInfo.CurrentCulture, "{0}{1}", containingElement.BaseUri, fragment); return new Uri(uriString); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload