Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml to Text Convert

I would like to write something in C# that takes Xml and converts it to plain text.

<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

Would become:

To Tove
From Jani
Heading Reminder
Body don't forget me this weekend!

Is there any thing already like this? and how would i go about doing this?

This is just ruffly the idea im going for still needs lots of work:

private void dataGridViewResult_SelectionChanged(object sender, EventArgs e)
        {
            if (this.dataGridViewResult.SelectedRows.Count > 0)
            {
                XslCompiledTransform xslt = new XslCompiledTransform();
                xslt.Load("SQL"); //.xml

                xslt.Transform("SQL","SQL"); //.xml, .html
                this.richTextBoxSQL.Text = this.dataGridViewResult.SelectedRows[0].Cells["SQL"].Value.ToString();
            }
        }
like image 464
Pomster Avatar asked Jun 11 '12 12:06

Pomster


People also ask

How do I open an XML file in text?

Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome". When you do, the file will open in a new tab.


1 Answers

The following XSLT script will do what you want:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="*">
        <xsl:for-each select="*">
            <xsl:value-of select="local-name()"/>
            <xsl:text> </xsl:text>
            <xsl:value-of  select="."/>
            <xsl:text>
</xsl:text>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Then you can apply the script using the XslCompiledTransform class as such:

private string transformXml(string sourceXmlText, string xsltText)
{
    XmlDocument sourceXmlDocument = new XmlDocument();
    sourceXmlDocument.LoadXml(sourceXmlText);
    XslCompiledTransform transformer = new XslCompiledTransform();
    XmlTextReader xsltReader = new XmlTextReader(new StringReader(xsltText));
    transformer.Load(xsltReader);
    MemoryStream outputStream = new MemoryStream();
    XmlWriter xmlWriter = XmlWriter.Create(outputStream, transformer.OutputSettings);
    transformer.Transform(sourceXmlDocument, null, xmlWriter);
    outputStream.Position = 0;
    StreamReader streamReader = new StreamReader(outputStream);
    return streamReader.ReadToEnd();
}

It's obviously more complex than the other solutions people have posted, but it has the major advantage of being able to easily change the script if you need to change the formatting.

like image 89
Steven Doggart Avatar answered Sep 25 '22 19:09

Steven Doggart