We need to parse an XML file with XSLT into a CVS file. The code below works but only if the fields in the XML are always constant.
The fields in the our XML file will always vary. How can I change my XSLT file so that it dynamically includes in the CSV file all the fields from the XML file?
XML:
<?xml version="1.0" encoding="iso-8859-1"?>
<data>
<row>
<customerID>06104539-463E-4B1A-231-34342343434</customerID>
<contactID>23434-99F2-4325-B228-6F343483469389FB</contactID>
<firstName>Jim</firstName>
<lastName>Smith</lastName>
</row>
<row>
<customerID>223434-463E-4B1A-231-A1E7EA248796</customerID>
<contactID>6675767-99F2-4325-B234328-6F83469389FB</contactID>
<specialID>112332</specialID>
<firstName>John</firstName>
<middleName>S.</middleName>
<lastName>Jones</lastName>
</row>
</data>
XSLT:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
customerID,contactID<br/>
<xsl:for-each select="data/row">
<xsl:value-of select="customerID"/>,<xsl:value-of select="contactID"/><br/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Here is the ASP.NET file that parses the files above:
<%@ Page Language="c#" %>
<%@ import Namespace="System.Xml" %>
<%@ import Namespace="System.Xml.Xsl" %>
<%@ import Namespace="System.Xml.XPath" %>
<%@ import Namespace="System.IO" %>
<%@ import Namespace="System.Text" %>
<script runat="server">
public void Page_Load(Object sender, EventArgs E) {
string xmlPath = Server.MapPath("test2.xml");
string xslPath = Server.MapPath("test2.xsl");
StreamReader reader = null;;
XmlTextReader xmlReader = null;
FileStream fs = new FileStream(xmlPath, FileMode.Open, FileAccess.Read);
reader = new StreamReader(fs,Encoding.UTF7);
xmlReader = new XmlTextReader(reader);
XPathDocument doc = new XPathDocument(xmlReader);
XslTransform xslDoc = new XslTransform();
xslDoc.Load(xslPath);
xslDoc.Transform(doc,null, Response.Output);
reader.Close();
xmlReader.Close();
}
</script>