我可以加载一个XDocument时使用predefined命名空间? [英] Can I use predefined namespaces when loading an XDocument?

查看:126
本文介绍了我可以加载一个XDocument时使用predefined命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常要处理包含命名空间的元素,但不声明命名空间的XML文档。例如:

I often have to deal with XML documents that contain namespaced elements, but doesn't declare the namespace. For example:

<root>
  <a:element/>
</root>

由于该preFIXa被从未分配一个命名空间URI,该文件是无效的。当我用下面的code加载这样的XML文档:

Because the prefix "a" is never assigned a namespace URI, the document is invalid. When I load such an XML document using the following code:

using (StreamReader reader = new StreamReader(new FileStream(inputFileName,    
       FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) {
            doc = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
}

它抛出一个异常,说明(正确地)该文件包含一个未声明的命名空间,而不是良好的。

it throws an exception stating (rightly) that the document contains an undeclared namespace and is not well-formed.

所以,我可以predefine默认命名空间preFIX - >命名空间URI对的解析器依傍? XmlNamespaceManager的看起来很有希望,但不知道如何将它应用到这种情况(或者,如果我可以)。

So, can I predefine default namespace prefix -> namespace URI pairs for the parser to fall back on? XMLNamespaceManager looks promising, but don't know how to apply it to this situation (or if I can).

推荐答案

您可以创建一个的XmlReader XmlParserContext 知道该命名空间;以下作品的XmlDocument 的XDocument

You can create an XmlReader with an XmlParserContext that knows about the namespaces; the following works for XmlDocument and XDocument:

class SimpleNameTable : XmlNameTable {
    List<string> cache = new List<string>();
    public override string Add(string array) {
        string found = cache.Find(s => s == array);
        if (found != null) return found;
        cache.Add(array);
        return array;
    }
    public override string Add(char[] array, int offset, int length) {
        return Add(new string(array, offset, length));
    }
    public override string Get(string array) {
        return cache.Find(s => s == array);
    }
    public override string Get(char[] array, int offset, int length) {
        return Get(new string(array, offset, length));
    }
}
static void Main() {
    XmlNamespaceManager mgr = new XmlNamespaceManager(new SimpleNameTable());
    mgr.AddNamespace("a", "http://foo/bar");
    XmlParserContext ctx = new XmlParserContext(null, mgr, null,
        XmlSpace.Default);
    using (XmlReader reader = XmlReader.Create(
        new StringReader(@"<root><a:element/></root>"), null, ctx)) {

        XDocument doc = XDocument.Load(reader);

        //XmlDocument doc = new XmlDocument();
        //doc.Load(reader);
    }
}

这篇关于我可以加载一个XDocument时使用predefined命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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