Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c# - Validating xml nodes, not the entire document

I'm working with some xml 'snippets' that form elements down the xml. I have the schema but I cannot validate these files because they are not complete xml documents. These snippets are wrapped with the necessary parent elements to form valid xml when they are used in other tools so I don't have much option in making them into valid xml or in changing the schema.

Is it possible to validate an element, rather than the whole document? If not, what workarounds could be suggested?

I'm working in C# with .NET 2.0 framework.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had a similar problem where I could only validate parts of my XML document. I came up with this method here:

private void ValidateSubnode(XmlNode node, XmlSchema schema)
{
    XmlTextReader reader = new XmlTextReader(node.OuterXml, XmlNodeType.Element, null);

    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ConformanceLevel = ConformanceLevel.Fragment;
    settings.Schemas.Add(schema);
    settings.ValidationType = ValidationType.Schema;
    settings.ValidationEventHandler += new ValidationEventHandler(XSDValidationEventHandler);

    using (XmlReader validationReader = XmlReader.Create(reader, settings))
    {     
        while (validationReader.Read())
        {
        }
    }
}

private void XSDValidationEventHandler(object sender, ValidationEventArgs args)
{
    errors.AppendFormat("XSD - Severity {0} - {1}", 
                        args.Severity.ToString(), args.Message);
}

Basically, I pass it an XmlNode (which I select from the entire XmlDocument by means of .SelectSingleNode), and an XML schema which I load from an embedded resource XSD inside my app. Any validation errors that might occur are being stuffed into a "errors" string builder, which I then read out at the end, to see if there were any errors recorded, or not.

Works for me - your mileage may vary :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...