C'è un modo più efficiente per trasformare un XDocument che già contiene un riferimento a un XSLT?

StackOverflow https://stackoverflow.com/questions/8346715

Domanda

Ho un file XML che contiene già un riferimento a un file XSLT.

sto guardando la conversione di questo file XML, in base alle regole di trasformazione a cui fa riferimento, in modo che possa poi creare un file PDF bello.

Sembra che posso eseguire l'effettiva trasformazione tramite System.Xml.Xsl.XslCompiledTransform, ma richiede che associo manualmente un XSLT prima di eseguire la trasformazione.

In base a quello che ho visto, ora devo tirare manualmente il riferimento XSLT dal XDocument (inizio difficile sotto):

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

Tuttavia, poiché l'XSLT è già fa riferimento all'interno del file XML stesso, suppongo che sto facendo troppo lavoro, e c'è un modo più efficiente per applicare la trasformazione.

C'è, o si tratta di ciò che si deve fare?

È stato utile?

Soluzione

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

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top