开发者

How to get the file position of an XSD error in the XML file?

I have the following code which successfully validates an XML file against an XSD schema:

    Try

   开发者_StackOverflow中文版     Dim val As New Xml.XmlReaderSettings With {.ValidationType = ValidationType.Schema}
        val.Schemas.Add(Nothing, "myvalidator.xsd")

        Using reader = XmlReader.Create("myfile.xml", val)
            While reader.Read
            End While
        End Using

        Console.WriteLine("XML validation succeeded.")

    Catch ex As Exception
        Console.WriteLine("XML validation failed." & vbCr & vbLf & "Error Message: " & ex.Message)
    End Try

A sample error I'm getting is

The element 'address' has invalid child element 'zip_code'. List of possible elements expected: 'address_line_2, address_line_3, city'.

When I'm validating a large XML file with hundreds of members who each have several addresses, this isn't enough information to pinpoint the problem. Is there a way to get a line number or file position or some other helpful piece of data to know where exactly the problem is happening in the original XML file? I realize XmlReader isn't reading the file the same way a text reader does, and the XML might be nicely formatted or on one giant line, so line numbers aren't necessarily the way to go. It would seem like I should be able to do something inside the While loop to know where the problem is, but I haven't found it yet.


First of all, do not use "ex.Message". It only shows you the text of the top-level exception. Use ex.ToString() instead.

Secondly, look at the properties of the XmlReader at the time of the exception. Also, look carefully at all of the properties of the XmlException you are being passed. It has LineNumber and LinePosition properties.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜