[英]C#: Line information when parsing XML with XmlDocument
What are my options for parsing an XML file with XmlDocument and still retain line information for error messages later on?使用 XmlDocument 解析 XML 文件并在以后仍保留错误消息的行信息时,我有哪些选择? (as an aside, is it possible to do the same thing with XML Deserialisation?) (顺便说一句,是否可以用 XML 反序列化做同样的事情?)
Options seem to include:选项似乎包括:
(Expanding answer from @Andy's comment) (从@Andy 的评论中扩展答案)
There is no built in way to do this using XmlDocument
(if you are using XDocument
, you can use the XDocument.Load()
overload which accepts LoadOptions.SetLineInfo
- see this question ).使用XmlDocument
没有内置的方法来执行此操作(如果您使用XDocument
,则可以使用接受LoadOptions.SetLineInfo
的XDocument.Load()
重载 - 请参阅此问题)。
While there's no built-in way, you can use the PositionXmlDocument
wrapper class from here (from the SharpDevelop project):虽然没有内置方法,但您可以从这里(来自SharpDevelop项目)使用PositionXmlDocument
包装类:
https://github.com/icsharpcode/WpfDesigner/blob/5a994b0ff55b9e8f5c41c4573a4e970406ed2fcd/WpfDesign.XamlDom/Project/PositionXmlDocument.cs https://github.com/icsharpcode/WpfDesigner/blob/5a994b0ff55b9e8f5c41c4573a4e970406ed2fcd/WpfDesign.XamlDom/Project/PositionXmlDocument.cs
In order to use it, you will need to use the Load
overload that accepts an XmlReader
(the other Load
overloads will go to the regular XmlDocument
class, which will not give you line number information).为了使用它,你将需要使用Load
接受过载XmlReader
(其它Load
重载会去正规XmlDocument
类,它不会给你行号信息)。 If you are currently using the XmlDocument.Load
overload that accepts a filename, you will need to change your code as follows:如果您当前正在使用接受文件名的XmlDocument.Load
重载,则需要按如下方式更改代码:
using (var reader = new XmlTextReader(filename))
{
var doc = new PositionXmlDocument();
doc.Load(reader);
}
Now, you should be able to cast any XmlNode
from this document to a PositionXmlElement
to retrieve line number and column:现在,您应该能够将本文档中的任何XmlNode
转换为PositionXmlElement
以检索行号和列:
var node = doc.ChildNodes[1];
var elem = (PositionXmlElement) node;
Console.WriteLine("Line: {0}, Position: {1}", elem.LineNumber, elem.LinePosition);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.