简体   繁体   中英

Element is not declared validation error post upgrading from .Net v4.5 to .Net v4.5.2

I understand that there are already many existing threads for the 'element not found' error for XML validation but I'm posting this as my problem is slightly different.

My code was running fine until it was on .Net v4.5. After upgrading the framework to v4.6.1, I started getting this error for each XML element in my xml file. Upon downgrading I found that the error started occurring from .Net framework v4.5.2 onwards. Below is my code:

XML - Book.xml

<?xml version="1.0" ?>
<!DOCTYPE book SYSTEM "Book.dtd">
<book>
    <title>The Lord of the Rings</title>
    <author>J.R.R. Tolkien</author>
    <isbn>1572810556</isbn>
</book>

DTD - Book.dtd

<!ELEMENT book (title, author, isbn)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>

C# Functions

public static void ReadXMLwithDTD()
{
    // Set the validation settings.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.DTD;
    settings.DtdProcessing = DtdProcessing.Parse;
    settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
    settings.IgnoreWhitespace = true;

    // Create the XmlReader object.
    XmlReader reader = XmlReader.Create("Book.xml", settings);

    // Parse the file.
    while (reader.Read())
    {
        Console.WriteLine("{0}, {1}: {2} ", reader.NodeType, reader.Name, reader.Value);
    }
}

private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
        Console.WriteLine("Warning: Matching schema not found.  No validation occurred." + e.Message);
    else // Error
        Console.WriteLine("Validation error: " + e.Message);
}

When run the code the callback throws validation errors (element not found) for all four XML elements - book, title, author and isbn.

Any help to fix this will be appreciated.

Thanks,

I'm a bit late to the party but I think I've found a solution by adding the following code right before settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

settings.XmlResolver = new XmlUrlResolver();

Starting with the .NET Framework 4.5.2, this setting has a default value of null.

Reference: https://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.xmlresolver(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM