如何使用.NET中的文件将XML转换为字符串?

时间:2010-03-05 03:04:23

标签: c# xml xslt

假设我有两个字符串:

  • 一个是XML数据
  • ,另一个是XSL数据。

如果您必须知道,xml和xsl数据存储在数据库列中。

如何在C#中转换XML w / o首先将xml和xsl保存为文件?我希望输出也是一个字符串(转换中的HTML)。

似乎C#更喜欢通过文件进行转换。我在XslCompiledTransform中找不到Load()的字符串输入重载。所以,这就是我要问的原因。

7 个答案:

答案 0 :(得分:37)

这就是我的用途。这是你的答案的组合。我投了这些灵感的答案:

string output = String.Empty;
using (StringReader srt = new StringReader(xslInput)) // xslInput is a string that contains xsl
using (StringReader sri = new StringReader(xmlInput)) // xmlInput is a string that contains xml
{
    using (XmlReader xrt = XmlReader.Create(srt))
    using (XmlReader xri = XmlReader.Create(sri))
    {
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(xrt);
        using (StringWriter sw = new StringWriter())
        using (XmlWriter xwo = XmlWriter.Create(sw, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML
        {
            xslt.Transform(xri, xwo);
            output = sw.ToString();
        }
    }
}

注意:xsl中需要此语句,以便以HTML格式输出:

<xsl:output method="html" omit-xml-declaration="yes" />

答案 1 :(得分:5)

如果您使用正确的习语,我花了很长时间(几年)才能弄清楚使用Stream和/或TextWriter的简洁代码。

假设transforminput是字符串:

StringWriter sw = new StringWriter();
using (XmlReader xrt = XmlReader.Create(new StringReader(transform))
using (XmlReader xri = XmlReader.Create(new StringReader(input))
using (XmlWriter xwo = XmlWriter.Create(sw))
{
   XslCompiledTransform xslt = new XslCompiledTransform();
   xslt.Load(xrt);
   xslt.Transform(xri, xwo);
}
string output = sw.ToString();

答案 2 :(得分:4)

答案 3 :(得分:1)

编辑:添加了使用块

// input-xml
string xmlinput = String.Empty;
// xslt
string xsltinput = String.Empty;
// output-xml
string xmloutput = String.Empty;

// Prepare input-xml
XPathDocument doc = new XPathDocument(new StringReader(xmlinput));

// Prepare XSLT
XslTransform xslt = new XslTransform();
// Creates a XmlReader from your xsl string
using (XmlReader xmlreader = XmlReader.Create(new StringReader(xsltinput)))
{
    //Load the stylesheet.
    xslt.Load(xmlreader);

    // transform
    using (StringWriter sw = new StringWriter())
    {
        xslt.Transform(doc, null, sw);

        // save to string
        xmloutput = sw.ToString();
    }
}

答案 4 :(得分:1)

我发送xml内容然后加载XSLT文档,应用转换然后返回新的xml。

public static string Transform(string xmlString)
{
    string output = String.Empty;
    try
    {
        // Load an XML string into the XPathDocument.
        StringReader rdr = new StringReader(xmlString);
        XPathDocument myXPathDoc = new XPathDocument(rdr);

        var myXslTrans = new XslTransform();
        //load the Xsl 
        myXslTrans.Load("XSLTFile.xslt");
        //create the output stream
        StringWriter sw = new StringWriter();
        XmlWriter xwo = XmlWriter.Create(sw);
        //do the actual transform of Xml
        myXslTrans.Transform(myXPathDoc, null, xwo);
        output = sw.ToString();
        xwo.Close();
        return output;
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: {0}", e.ToString());
        throw;
    }
}

注意:“XSLTFile.xslt”它被添加到解决方案中并将属性“Copy to Output Directory”设置为“Always always”。

答案 5 :(得分:0)

受Robert Rossney的回答启发的VB.Net版本:

Private Function TransformXML(XMLPath As String, XSLPath As String) As String
    Dim XSLT As XslCompiledTransform = New XslCompiledTransform()
    Dim sWriter As StringWriter = New StringWriter
    Dim xReader As XmlReader = XmlReader.Create(XMLPath)

    Using xWriter As XmlWriter = XmlWriter.Create(sWriter)
        XSLT.Load(XSLPath)
        XSLT.Transform(xReader, xWriter)
    End Using
    Return sWriter.ToString
End Function

答案 6 :(得分:-1)

我会使用XmlReader.Create(DatabaseBlobStream)XmlWriter.Create(StringBuilder)重载。使用以下DatabaseBlobStream对象

DatabaseBlobStream.cs

internal class DatabaseBlobStream : Stream
{
    private readonly IDataReader reader;
    private readonly int columnIndex;
    private long streamPosition;

    internal DatabaseBlobStream(IDataReader reader, int columnIndex)
    {
        this.reader = reader;
        this.columnIndex = columnIndex;
    }

    public override bool CanRead
    {
        get
        {
            return reader.GetFieldType(columnIndex) == typeof (byte[])
                   && !reader.IsDBNull(columnIndex);
        }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void Flush()
    {
        throw new Exception("This stream does not support writing.");
    }

    public override long Length
    {
        get { throw new Exception("This stream does not support the Length property."); }
    }

    public override long Position
    {
        get
        {
            return streamPosition;
        }
        set
        {
            streamPosition = value;
        }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        if (reader.IsDBNull(columnIndex))
            return 0;

        int bytesRead = (int)reader.GetBytes(columnIndex, streamPosition + offset, buffer, 0, count);
        streamPosition += bytesRead;
        return bytesRead;
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        throw new Exception("This stream does not support seeking.");
    }

    public override void SetLength(long value)
    {
        throw new Exception("This stream does not support setting the Length.");
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        throw new Exception("This stream does not support writing.");
    }

    public override void Close()
    {
        try
        {
            reader.Close();
        }
        finally
        {
            base.Close();
        }
    }

    protected override void Dispose(bool disposing)
    {
        try
        {
            reader.Dispose();
        }
        finally
        {
            base.Dispose(disposing);
        }
    }
}