XMLReader:如何捕获xml文件中的语法错误?

时间:2010-05-07 05:57:44

标签: c# xml

我有一个包含语法错误的XML文件。例如。

<Viewport thisisbad Left="0" Top="0" Width="1280" Height="720" >

当我创建XML阅读器时,它不会抛出任何错误。我有办法自动进行语法检查,比如XMLDocument吗?

我尝试过设置各种XmlReaderSettings标志,但没有发现任何有用的东西。

1 个答案:

答案 0 :(得分:2)

要使用XmlReader检查XML文档是否格式正确,您必须实际读取文档。

在C#中,这样做:

var txt = "<Viewport thisisbad Left='0' Top='0' Width='1280' Height='720' >";
XmlReader reader = XmlReader.Create(new StringReader(txt));
while (reader.Read()) { }

运行该代码得到的结果是:

Exception: System.Xml.XmlException: 'Left' is an unexpected token. The expected token is '='. Line 1, position 21.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args)
   at System.Xml.XmlTextReaderImpl.ThrowUnexpectedToken(String expectedToken1, String expectedToken2)
   at System.Xml.XmlTextReaderImpl.ParseAttributes()
   at System.Xml.XmlTextReaderImpl.ParseElement()
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlTextReaderImpl.Read()

another answer中所述,无需管理一堆元素。 XmlReader为您完成。

您写道:

  

当我创建XML阅读器时,它不会抛出任何错误。我有办法自动进行语法检查,比如XMLDocument吗?

要实现的关键是XmlReader是读取xml 的对象。如果你只是创建它,它还没有读取任何xml,所以当然它无法告诉你xml(它还没有读过)是否有效。

要快速检查XML的语法或格式良好,请在XmlReader上调用Read(),直到它返回null。它会为你做检查。但是,要意识到,一旦你做到了这一点,XmlReader就在文档的最后。您需要重置才能实际读取和检查xml的内容。我见过的大多数应用程序同时进行。换句话说,应用程序检查内容,并将“语法检查”委托给读者:

XmlReader reader = XmlReader.Create(sr);
while (reader.Read())  // will throw if not well-formed
{
    switch (reader.NodeType)
    {
        case XmlNodeType.XmlDeclaration:
            ...
            break;
        case XmlNodeType.Element:
            ...
            break;
        case XmlNodeType.Text:
            ...
            break;
        ...
    }
}
相关问题