After reading LoadOptions.SetBaseUri it is apparent that LINQ to XML uses Annotations to achieve the setting of the BaseUri
property. This is unfortunate as the annotation is of the internal type System.Xml.Linq.BaseUriAnnotation
, which you do not have access to. My suggestion would be to perhaps set your own annotation which would use either its value or the value of BaseUri
if it was not null
.
public class MyBaseUriAnnotation
{
public XObject XObject { get; private set; }
private string baseUri = String.Empty;
public string BaseUri
{
get
{
if (String.IsNullOrEmpty(this.baseUri))
return this.XObject.BaseUri;
return this.baseUri;
}
set { this.baseUri = value; }
}
public MyBaseUriAnnotation(XObject xobject)
: this(xobject, String.Empty)
{
}
public MyBaseUriAnnotation(XObject xobject, string baseUri)
{
if (xobject == null) throw new ArgumentNullException("xobject");
this.XObject = xobject;
this.baseUri = baseUri;
}
}
You can then use a method to add the annotation to an XDocument
you parse on your own:
public static XDocument XDocumentFromString(string baseUri, string xml)
{
var xdoc = XDocument.Parse(xml);
xdoc.AddAnnotation(new MyBaseUriAnnotation(xdoc, baseUri));
return xdoc;
}
And then whenever you'd like to find the BaseUri
, you could use an extension method to retrieve the correct BaseUri
:
public static string FindBaseUri(this XObject xobject)
{
if (xobject == null) throw new ArgumentNullException(xobject);
var baseUri = xobject.Annotation<MyBaseUriAnnotation>();
return baseUri != null ? baseUri.BaseUri : xobject.BaseUri;
}