Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top