SOF User
SOF User

Reputation: 7830

XML to HTML in .net

<?xml version="1.0" encoding="UTF-8"?>
<Advanced_IP_scanner>
    <row ip="10.10.1.4" status="1" name="remote003.domain.local" has_http="0" has_https="0" has_ftp="0" has_radmin_1="0" has_radmin_2="0" has_radmin_3="0" has_radmin_4="0">
        <share name="ADMIN$"/>
        <share name="C$"/>
        <share name="IPC$"/>
    </row>
    <row ip="10.10.1.12" status="1" name="remote005.domain.local" has_http="0" has_https="0" has_ftp="0" has_radmin_1="0" has_radmin_2="0" has_radmin_3="0" has_radmin_4="0">
        <share name="ADMIN$"/>
        <share name="C$"/>
        <share name="IPC$"/>
    </row>   
</Advanced_IP_scanner>

How can i convert above XML into simple HTML table to list all the rows and row headers so that I can show on my webpage.

Upvotes: 2

Views: 2421

Answers (2)

Michael Kay
Michael Kay

Reputation: 163322

Here's an example of what a suitable stylesheet might look like. You'll have to adapt it of course depending on the HTML you actually want to produce.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="Advanced_IP_Scanner">
    <html>
      <head>
        <title>Ip Scanner Table</title>
      </head>
      <body>
        <table>
          <thead>
            <tr>
              <th>...</th>
              <th>...</th>
              ...
            </tr>
          </thead>
          <tbody>
             <xsl:apply-templates/>
          </tbody>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="row">
    <tr>
      <td><xsl:value-of select="@ip"/></td>
      <td><xsl:value-of select="@name"/></td>
      <td><xsl:value-of select="@status"/></td>
      <td><xsl:value-of select="@has-http"/></td>
      ....
    </tr>
  </xsl:template>
</xsl:stylesheet>

There are several XSLT processors available for .NET. The Microsoft one comes bundled with .NET, and only supports XSLT 1.0 (which is fine for a simple task like this, but runs out of steam on more complex transformations.) There are two independent processor that support XSLT 2.0 - my own Saxon product, which is well established and widely used, and a more recent arrival, XQSharp.

Upvotes: 1

Donut
Donut

Reputation: 112815

You should use XSLT, it's designed specifically for this task.
An example of what your code might look like is as follows (thanks to this answer and this page):

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);

Hope this helps. If you have further XSLT questions, don't hesitate to ask here.

Upvotes: 4

Related Questions