我可以指定一个baseURI为一个XDocument? [英] Can I assign a BaseUri to an XDocument?

查看:152
本文介绍了我可以指定一个baseURI为一个XDocument?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从磁盘加载XML文档到一个XDocument,那的XDocument具有包含原始XML文档的磁盘上的位置,一个现成的唯一的财产的基本URI。换句话说,

When I load an XML document from disk into an XDocument, that XDocument has a ready-only property BaseUri that contains the original XML document's location on disk. In other words,

XDocument doc = XDocument.Load(@"c:\temp\doc.xml");
Console.Out.WriteLine(doc.BaseUri);
// Outputs "file:///c:/temp/doc.xml"

如果我从头开始创建一个新的XDocument,它没有基本URI。例如:

If I create a new XDocument from scratch, it has no BaseUri. For example:

XDocument doc = new XDocument(new XElement("test"));
Console.Out.WriteLine(doc.BaseUri);
// Outputs nothing



我可以指定这个新的XDocument基本URI?我希望能够生成新的文件,将它们分配名称,并轻松地与他们一起通过这些名字。

Can I assign this new XDocument a BaseUri? I'd like to be able to generate new documents, assign them names, and easily pass those names along with them.

推荐答案

LoadOptions.SetBaseUri 的很明显,后LINQ到XML使用注释实现的基本URI属性的设置。这是不幸的,因为注释是内部型 System.Xml.Linq.BaseUriAnnotation ,你不访问的。我的建议是也许是设置自己的注释它将使用其任一值或基本URI 如果不是

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;
    }
}



然后,您可以使用一种方法来添加这个注解一个的XDocument 你对你自己的分析:

public static XDocument XDocumentFromString(string baseUri, string xml)
{
    var xdoc = XDocument.Parse(xml);
    xdoc.AddAnnotation(new MyBaseUriAnnotation(xdoc, baseUri));
    return xdoc;
}

然后,只要你想找到基本URI ,您可以使用扩展方法来检索正确的基本URI

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;
}

这篇关于我可以指定一个baseURI为一个XDocument?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆