简体   繁体   中英

Validate xml with xsd in C# and replace invalid data with null value

如何使用C#使用.xsd文件验证.xml文件中的数据并将无效数据替换为空值?

Look at the XmlSchemaValidator class . While it's not easy to use, it is very powerful.

It works via a "push" model. The API informs you what kind of XML would be valid at the current point in the validation. You then supply a valid piece of XML (element, attribute, etc), and ask again, what would be valid now . I have used this to create sample XML that conforms to a set of schemas.

Although I haven't tried it, I suppose you could feed your input XML to the validator, then pass some "empty" XML once you reach an invalid point in the parse.

In .NET 3.5 to validate just use the following code

    public bool Validate(XmlReader xmlInput, XmlReader schemaDocument)
    {
        var xmlSchemaSet = new XmlSchemaSet();
        xmlSchemaSet.Add("", schemaDocument);
        try
        {
            var doc = XDocument.Load(xmlInput);
            bool valid = true;
            doc.Validate(xmlSchemaSet, (o, e) =>
            {
                valid = false;
            });
            return valid;
        }
        catch (Exception e)
        {
            return false;
        }
    }

but to correct your document, you should use XmlReader's methods and custom verification, I consider.

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