我在我的XML中有一个类似内容。
<myElement myAttribute="myNamespacePrefix:foobar"/>
该档案中有一只Xmlns声明:
<xmlns:myNamespacePrefix="http://www.mydomain.com/blah#"/>
I want to make a URI from the value of myAttribute.
我想:
http://www.mydomain.com/blah#foobar
Sounds simple, doesn t it?
因此,简单的解决办法是什么?
我在《框架》或“MSDN”中找不到任何东西,因此,我只得写这一无一不在的泡影:
public static Uri GetUri(string value, XElement containingElement)
{
if (value.Contains(":"))
{
var prefix = String.Concat(value.TakeWhile(c => c != : ));
XNamespace ns;
if (containingElement.GetNamespaceOfPrefix(prefix) != null)
ns = containingElement.GetNamespaceOfPrefix(prefix);
else ns = containingElement.GetDefaultNamespace();
var localName = String.Concat(value.SkipWhile(c => 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);
}
}