*The following post is on VS 2008 & .NET Framework 3.5
Say we have an assembly called "MyAssembly" which could be seen on the project settings.
Let's first start with reading anything from embedded resources:
If we have a resource, and .xml file in this case, named as "MyXmlFile.xml", the resource name for this file would be "MyAssembly.MyXmlFile.xml"
Here's the code that streams the contents of this file:
Stream xmlStream = a.GetManifestResourceStream("CRFSCommandLine.WorkOrderTransform.xsl");
Now we have a stream that we can play with, let's now just display what it has in it:
StreamReader sr = new StreamReader(xmlStream);
Console.WriteLine(sr.ReadToEnd());
Now let's move on to doing validation and transform:
Here's what a validation would look like
Stream xsdStream= a.GetManifestResourceStream("MyAssembly.MySchema.xsd");
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchema x = XmlSchema.Read(schemaStream,
new ValidationEventHandler(HandleValidationEvent));
schemas.Add(x);
readerDoc.WhitespaceHandling = WhitespaceHandling.None;
//XmlValidatingReader is obsolete with .NET 3.5, we need to use XmlReader and //appropriate XmlReaderSettings settings
XmlReaderSettings validationReaderSettings = new XmlReaderSettings();
validationReaderSettings.ValidationType = ValidationType.Schema;
validationReaderSettings.Schemas.Add(schemas);
validationReaderSettings.ValidationEventHandler += new ValidationEventHandler(HandleValidationEvent);
//docReader is the XmlReader we have for the XML document we want to validate
XmlReader newReader = XmlReader.Create(readerDoc, validationReaderSettings);
while ( newReader.Read());
newReader.Close();
This should do the trick, below is what the transformation looks like:
XmlDocument originalDoc = new XmlDocument();
originalDoc.Load(fileName);
XslCompiledTransform trans = new XslCompiledTransform(true);
trans.Load(new XmlTextReader(transformStream));
XmlTextWriter xtw = new XmlTextWriter("TransformOutput.xml", Encoding.Unicode);
xtw.Formatting = Formatting.Indented;
trans.Transform(originalDoc.CreateNavigator(), xtw);
StringWriter sw = new StringWriter();
trans.Transform(originalDoc.CreateNavigator(), null, sw); //sw.ToString() would be //the string output here
That's all
Thursday, November 19, 2009
Reading XSD & XSL files from embedded resources of an assembly
Labels:
.NET 3.5,
embedded resources,
visual studio 2008,
vs2008,
xsd,
xsl
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment