Scripting: How to do a XML validation

 
0 Likes

Even if Micro Focus Service Virtualization doesn't have built-in support for XML validation, you can still do it thanks to it's scripting capabilities.

Let's consider HTTP based service for now. The idea is to split XML validation and regular simulated response creation to two virtual services. So for this to work you need to create additional Binary over HTTP virtual service, which will be doing XML validation. If validation passes, you can forward the content to the virtual service able to produce regular response.

Forwarding itself can be done via Binary over HTTP Service Call Activity or directly in a C# script. As we want to avoid scripting for now, let's assume we'll do it in the SCA.

C# script example:

 

public class CSharpRule { 
    private const string TargetNamespace = "http://www.example.com"; 
    private const string SchemaFile = @"c:\example\path\to\xsd\example.xsd"; 
    public static void Execute(HpsvRootObject sv) { 
        byte[] binaryData = Convert.FromBase64String(sv.Request.BinaryContent.Data); 
        Dictionary<XmlSeverityType, string> validationResult = ValidateXml(binaryData); 
        if (validationResult.ContainsKey(XmlSeverityType.Error)) { 
            // put the code here on what to do in case validation contains errors
            sv.Response.HTTPOutputParameters.StatusCode = 500;
        } else { 
            // validation passed! Let's just enable SCA to forward request
            sv.Activities[0].Enabled = true; 
        } 
    } 
    
    private static Dictionary<XmlSeverityType, string> ValidateXml(byte[] request) { 
        Dictionary<XmlSeverityType, string> validationResults = new Dictionary<XmlSeverityType, string>(); 
        XmlReaderSettings xmlReaderSettings = new XmlReaderSettings(); 
        xmlReaderSettings.Schemas.Add(TargetNamespace, SchemaFile); 
        xmlReaderSettings.ValidationType = ValidationType.Schema;
        xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler((sender, e) => validationEventHandler(sender, e, validationResults));
        // validate!
        XmlReader books = XmlReader.Create(new MemoryStream(request), xmlReaderSettings); while (books.Read()) { 
        } 
        
        return validationResults; 
    } 
    
    static void validationEventHandler(object sender, ValidationEventArgs e, Dictionary<XmlSeverityType, string> validationResults) { 
        validationResults.Add(e.Severity, e.Message); 
    } 
}

Labels:

How To-Best Practice
Comment List
Related
Recommended