简体   繁体   中英

How to validate xml, not containing xmlns=…, with c# XmlSerializer?

I am working with Mismo 2.3.1, dtd based schema. I converted the dtd to xsd and then generated c# code to serialize/deserialze object representations of the xml doc.

Given a valid mismo 2.3.1 xml doc, I can deserialize into my generated C# class.

I have code working to use XmlSerializer along with XmlReaderSettings and XmlSchmeas collection, reading in my converted xsd.

If I put xmlns="http://mySchema..." in the root element, and try to validate intentionally invalid xml, works as expected, my validation event gets pinged with accurate description.

If I take out the xmlns attribute, then i get "could not find schema information for element [my root element]"

Any idea on how to validate xml that comes in without the xmlns spec? Any settings to say to the serializer "use this schema when you come across this element"?

Thanks in advance!

static void Main() {
    var settings = new XmlReaderSettings();
    settings.NameTable = new NameTable();

    var nsMgr = new XmlNamespaceManager(settings.NameTable);
    nsMgr.AddNamespace("", "http://example.com/2013/ns"); // <-- set default namespace

    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add(null, @"C:\XSDSchema.xsd"); // <-- set schema location for the default namespace

    var parserCtx = new XmlParserContext(settings.NameTable, nsMgr, XmlSpace.Default);

    using (var reader = XmlReader.Create(@"C:\file.xml", settings, parserCtx)) {
        var serializer = new XmlSerializer(typeof(Foo));
        Foo f = (Foo)serializer.Deserialize(reader);
    }
}

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