Search code examples
xmlpowershellschemaxsd-validation

Generate an xml schema from a variable (like a here-string)


Ultimately, I'm wondering if it's possible to validate an Xml file against a schema that's contained in a here-string variable (rather than an already-existing .xsd file).

  • I've found several examples online and have read through much of the [System.Xml.Schema] documentation and can find numerous examples of how to create an Xml schema from an .xml file (or use an already-existing .xsd file), but I can't find anything about generating and using a schema that's contained in a here-string variable.
  • None of the (seemingly) applicable classes I've come across (XmlReader, XmlTextReader, XmlSchema, etc) have a constructor or method overload that works similar to XmlDocument.LoadXml(String), which can accept a here-string containing Xml.



Am I missing something, or am I stuck with having to create an .xsd file if I want to validate an XmlDocument instance against a schema?

  • My concern with creating an .xsd file (in the environment I'm working with) is that write permissions to XYZ folder have the potential to be denied.

Solution

  • System.Xml.Schema.XmlSchema has a Read method that allows you to take input from a System.IO.TextReader, and therefore from a System.IO.StringReader, and therefore from a String.

    $xmlSchemaText = @"
    <schema xml here>
    "@
    
    $stringReader = [System.IO.StringReader]::new($xmlSchemaText)
    
    $xmlSchema = [System.Xml.Schema.XmlSchema]::Read($stringReader)