Jam*_*lak 5 .net c# xml linq xml-namespaces
我经常必须处理包含命名空间元素但不声明命名空间的XML文档。例如:
<root>
<a:element/>
</root>
Run Code Online (Sandbox Code Playgroud)
因为从未为前缀“ a”分配名称空间URI,所以文档无效。当我使用以下代码加载这样的XML文档时:
using (StreamReader reader = new StreamReader(new FileStream(inputFileName,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) {
doc = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
}
Run Code Online (Sandbox Code Playgroud)
它抛出一个异常(正确地),指出该文档包含未声明的名称空间且格式不正确。
因此,我可以预定义默认的名称空间前缀->名称空间URI对,以使解析器可以使用吗?XMLNamespaceManager看起来很有前途,但是不知道如何将其应用于这种情况(或者如果可以的话)。
您可以XmlReader使用XmlParserContext知道名称空间的来创建一个;以下工程XmlDocument和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);
}
}
Run Code Online (Sandbox Code Playgroud)