6

I have an XML file that already contains a reference to an XSLT file.

I'm looking at converting this XML file, according to the referenced transformation rules, so that I can then create a nice PDF file.

It appears that I can perform the actual transform via System.Xml.Xsl.XslCompiledTransform, but it requires that I manually associate an XSLT before I perform the transform.

Based on what I've seen, I must now manually pull the XSLT reference from the XDocument (rough start below):

xmlDocument.Document.Nodes()
   .Where(n => n.NodeType == System.Xml.XmlNodeType.ProcessingInstruction)

However, since the XSLT is already referenced within the XML file itself, I assume I'm doing too much work, and there's a more efficient way to apply the transform.

Is there, or is this what one has to do?

defau1t
  • 10,593
  • 2
  • 35
  • 47
James Skemp
  • 8,018
  • 9
  • 64
  • 107

3 Answers3

1

If you were to use the Saxon XSLT processor rather than the Microsoft one, you could use the method XsltCompiler.CompileAssociatedStylesheet().

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
1

There is no more efficient way to do that. You have to retrieve href to xslt from your xml before transforming it.

Similar question here : XslTransform with xml-stylesheet

Community
  • 1
  • 1
Romain Meresse
  • 3,044
  • 25
  • 29
0

I wrote the following runtime extention to help with this. I haven't tested using a reference xsl in the xml yet, but otherwise it should be good.

<Runtime.CompilerServices.Extension()>
Public Function XslTransform(XDocument As XDocument, xslFile As String) As XDocument
    If String.IsNullOrWhiteSpace(xslFile) Then
        Try
            Dim ProcessingInstructions As IEnumerable(Of XElement) = From Node As XNode In XDocument.Nodes
                                                                     Where Node.NodeType = Xml.XmlNodeType.ProcessingInstruction
                                                                     Select Node
            xslFile = ProcessingInstructions.Value
        Catch ex As Exception
            ex.WriteToLog(EventLogEntryType.Warning)
        End Try
    End If
    XslTransform = New XDocument
    Try
        Dim XslCompiledTransform As New Xml.Xsl.XslCompiledTransform()
        XslCompiledTransform.Load(xslFile)
        Using XmlWriter As Xml.XmlWriter = XslTransform.CreateWriter
            Using XMLreader As Xml.XmlReader = XDocument.CreateReader()
                XslCompiledTransform.Transform(XMLreader, XmlWriter)
                XmlWriter.Close()
            End Using
        End Using

        Return XslTransform
    Catch ex As Exception
        ex.WriteToLog
        XslTransform = New XDocument()
        Throw New ArgumentException("XDocument failted to transform using " & xslFile, ex)
    End Try
End Function
VoteCoffee
  • 4,692
  • 1
  • 41
  • 44