我可以加载一个XDocument时使用predefined命名空间? [英] Can I use predefined namespaces when loading an XDocument?
问题描述
我经常要处理包含命名空间的元素,但不声明命名空间的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屋!