I often have to deal with XML documents that contain namespaced elements, but doesn't declare the namespace. For example:
<root>
<a:element/>
</root>
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.
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).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…