Use Java, MSXML convert XML to HTML

zhaozj2021-02-17  50

Converting XML to HTML Using Sun's Java API for XML Processing and Microsoft's MSXML 3.0 API

By Robert Galante

Introduction

This article describes two solutions that I have employed in applications to generate custom reports. My solutions convert XML data to HTML using XSL Transformations (XSLT). XML is an eXtensible Markup Language that is used as a data-exchange format between applications. XSL is an eXtensible Stylesheet Language that is used to present and lay out XML data in a browser. XSLT is a programming language that facilitates the transformation of XML data to its HTML equivalent before it is displayed in a browser. The first solution uses Sun's Java API for XML Processing (JAXP) to convert XML to HTML. The latest production version of the JAXP is version 1.1. The second solution uses Microsoft's MSXML 3.0 API to convert XML to HTML. (Microsoft XML [MSXML) is an XSLT processor that works with the Internet Explorer Browser and INCLUDES An XML Parser and XPath Processor.) Some of The Benefits of these IMPLEMENTATIONS FOLLOW.

XML data is derived from the existing application. As a result, the same XML data may be used by other applications, making the application and the data more useful. The presentation layer of the reports is separated from the business objects layer. Consequently, the report-generation utility may be used by other applications, including a Web server application. If the layout of the report is modified, the application does not have to be recompiled and linked. Only the XSL templates have to be modified. After I describe each solution, I present some of my observations and suggestions Note:.. This article assumes that the reader already has some knowledge of XML and XSL See the links at the bottom of this article for references to technical reports about XML and XSL Using Sun's Java. Api for XML TO HTML JAXP 1.1 Consists of Three Class Libraries. Their File Format (JAR) Files. Their File Names Are Jaxp.jar, Crimson.jar, And XAL an.jar. The final release supports the latest XML standards, including version 2.0 of the Simple API for XML (SAX 2.0), and Level 2 of the Document Object Model (DOM Level 2). Also, it includes integrated support for XSL Transformations (Xslt). I Recommend That You Install Version 1.3 of the Java Development Kit (JDK) WHEN USING JAXP 1.1. When I Use Version 1.2 of the JDK, My Application Displays a Minor, Non-Fatal Error Message When IT Shuts Down. THIS behavior is caused by the JDK, not the application, and version 1.3 resolves this problem. JAXP InstallationDecompress the zip or tar file and copy the three JAR files to the following subdirectory in your system's JDK directory. On my Windows machine the subdirectory is as follows .

C: /jdk1.3/libYou must add these JAR files to your CLASSPATH in order to use them Remember to observe case in the filenames Alternatively, you may copy the three class libraries to the Java extensions directory - C:.. / Jdk1 . .3 / jre / lib / ext I prefer the former installation location, but you are free to choose Report Generator class -. RepGen.java and RepGen.classThe report generator is a very simple class that wraps the functionality of the JAXP Transformer object . Applications create an instance of the report generator object and request reports with the buildReport method. The buildReport method takes an XML data string and the name of the XSL template file, which will be used to convert the XML data. It builds the requested report using the JAXP Transformer object, and displays it in the default browser on the target machine. The user prints the HTML page with the standard browser print function. The user saves the HTML page to another file from the browser window, using the "Save As " menu option in the browser's File menu. The RepGen class is a Java Bean. It has properties that allow the user to get and set the XML data string and the XSL template filename. It has two methods that allow the user to build the HTML page . Both methods have the name buildReport. The first method allows the user to specify the XML data string and XSL template filename as parameters. The second method uses the XML data string and XSL template filename that are set by the properties. The source code for The Repgen Class Follows.

Package com.fleet.utilities.repgen;

// Imported Jaxp Transformer (TRAX) CLASSES

Import javax.xml.transform.transformerfactory;

Import javax.xml.transform.transformer;

Import javax.xml.transform.stream.streamsource; import javax.xml.transform.Stream.StreamResult;

Import javax.xml.transform.transformerexception;

Import javax.xml.transform.transformerConfigurationException;

// Imported Java Classes

Import Java.io.stringReader;

Import java.io.fileReader;

Import java.io.bufferedreader;

Import java.io.fileoutputstream;

Import java.io.filenotfoundexception;

Import java.io.ioException;

Import java.io.serializable;

// Import The Browserlauncher Class

Import com.fleet.utilities.repgen.browserlauncher;

/ *

* Use the trax interface to Perform a Transformation In The SimpleSt Manner Possible

* (3 STatements).

* /

Public Class Repgen IMPLEMENTS Serializable

{

String sxml;

String sxsltemplate;

Public string getXml () {return sxml;}

Synchronized public void setXML (String SMLDATA) {

SXML = SXMLDATA;

}

Public string getXSLTemplate () {return sxsltemplate;}

SYNCHRONIZED PUBLIC VOID SetXSLTemplate (String SXSLFILE) {

SxSlTemplate = SXSLFILE;

}

// make Sure The BuildReport Method Is Thread-Safe.

Synchronized Public Void BuildReport (String SXMLDATA, STRING SXSLFILE)

THROWS TRANSFORMEREXCETION, TRANSFORMERCONFIGURATIONException,

FilenotFoundException, IOException

{

// Create An Output File with The Same Name as The XSL Template File,

// But with an extension of ".html".

String soutfile;

Int idot = sxslfile.lastIndexof (".");

IF (idot! = -1) {

Soutfile = SXSLFILE.SUBSTRING (0, IDOT) ".html";

} else {

Soutfile = SXSLFILE ".html";

}

// Initialize the bean profment.

SXML = SXMLDATA;

SxSlTemplate = SXSLFILE;

// use the static transformerfactory.newinstance () Method to instantiate // a transformerfactory. The javax.xml.transform.transformerFactory

// system property setting determines the actual class to instantiate -

// org.apache.xalan.transformer.transformerImpl.

TransformerFactory Tfactory = TransformerFactory.newInstance ();

// use the transformerfactory to instantiate a transformer tria Will Work with

// The Style Sheet You Specify. This Method Call Also Processes The Style Sheet

// INTO A Compiled Templates Object.

Transformer Transformer = TFactory.NewTransformer (SXSLTemplate);

// use the transformer to apply the associated templates object to an xml document

// and write the output to a file with the same name as the xsl template file what

// was passed in sxslfile.

Transformer.Transform (New StringReader (NEW STRINGREADER (SXML),

New StreamResult (New FileoutputStream (Soutfile));

// Now, launch the default browser with the html result.

Browserlauncher.OpenURL (Soutfile);

}

// make Sure The BuildReport Method Is Thread-Safe.

Synchronized public void buildreport ()

THROWS TRANSFORMEREXCETION, TRANSFORMERCONFIGURATIONException,

FilenotFoundException, IOException

{

// Create An Output File with The Same Name as The XSL Template File,

// But with an extension of ".html".

String soutfile;

Int idot = sxsltemplate.lastIndexof (".");

IF (idot! = -1) {

Soutfile = sxsltemplate.substring (0, idot) ".html";

} else {

Soutfile = SXSLTEMPLATE ".html";

}

// use the Same Three Lines to Transform The XML String To HTML.

TransformerFactory Tfactory = TransformerFactory.newInstance ();

Transformer Transformer = Tfactory.NewTransformer (New StreamSource), Transformer.Transform (New StringRead (New StringReader),

New StreamResult (New FileoutputStream (Soutfile));

// Now, launch the default browser.

Browserlauncher.OpenURL (Soutfile);

}

// conncture

Public repgen () {}

// include a static main function for testing.

Public static void main (string [] args)

THROWS TRANSFORMEREXCETION, TRANSFORMERCONFIGURATIONEXCEPTION,

FilenotFoundException, IOException

{

IF (args.length! = 2) {

System.err.Println ("Usage: java com.fleet.utilities.repgen.repgen source style");

System.exit (1);

}

Repgen rgobject = new repgen ();

BufferedReader Br = New BufferedReader (New FileReader (Args [0]));

String sline;

Stringbuffer sbuffer = new stringbuffer ();

While ((sline = br.readline ())! = null) {

SBuffer.Append (sline "/ n");

}

RgObject.buildreport (sbuffer.tostring (), args [1]);

}

}

The buildReport method performs the transformation from XML to HTML. First, the method creates an instance of the TransformerFactory class. Then, it requests a Transformer object from the class factory. The Transformer object has a "transform" method that uses a StreamSource object for input and a StreamResult object for output. The JAXP Transformer classes define and implement these stream classes. See the import statements in the code above for a list of the classes that are imported by the RepGen class. The StreamSource class has many constructors. One of these constructors takes a StringReader object and converts it to a StreamSource object. We pass our XML string through the StringReader object's constructor when we create the StreamSource object. The StreamResult class has many constructors. One of these constructors outputs text to a FileOutputStream object. The BUILDREPORT METHOD Produces An HTML Filename from The XSL Template FileName, But Changs The Extension TO ".html." The n, it passes this html filename to the fileoutputstream Object '

s constructor, which is passed to the transform method via a new StreamResult object. The transform method converts the XML string to HTML and writes the results to the output file. See the JAXP documentation that comes with the distribution for more details on these classes. Or click on the following link to view various references to JAXP online documentation. http://java.sun.com/xml/xml_jaxp.html Our example displays the results in a Web browser using the BrowserLauncher class. The BrowserLauncher class is a simple utility that encapsulates the details about launching the default browser. A programmer named Eric Albert was kind enough to publish this class on his Stanford University Web site. I have included this class in the RepGen JAR file. See the links below to download the source for The Browserlauncher Class. on Windows Machines, The Browserlauncher Class Uses The Default Browser. on Unix Machines, The Browserlauncher Class Assums That Netscape is The default browser. The rep Gen class is distributed as a JAR file, which is called RepGen.jar. Add this jar file to your CLASSPATH. Test the RepGen class with the following command. Java com.fleet.utilities.repgen.RepGen Report.xml Report.xsl You will see results displayed as shown below in your browser. I have included the sample XML and XSL files with the source code download. As you can see in the command above, they are called report.xml and report.xsl. Make sure these files are in the current directory when you execute the command. Otherwise, you will have to specify the complete system path and filename for each file. The following code fragment illustrates an example of how to use the RepGen class.import com.fleet.utilities. Repgen. *;

Static Public Void Main (String Args []) {

Repgen rgobject;

StringBuffer SXML = New StringBuffer ();

StringBuffer sxslfile = new stringbuffer ();

// Add some code here to build the xml string.

// this code will be diffrecia.

// for now, Hard-Code Some Data.

SXML.APpend ("");

SXML.Append ("..."); // code removed for break.

SXSLFILE = "SalesReport.xsl";

Try {

RgObject = new repgen ();

// this method transforms the xml to html and pops up the default browser.

RgObject.buildReport (SXML, SXSLFILE);

} catch (filenotfoundexception e) {

} catch (transformerconfigurationException e) {

} catch (transformerexception e) {

} catch (exception e) {

}

}

The RepGen class is very simple to use. First, create your XSL template file and your XML data string. Then create an instance of the RepGen class. Finally, call the buildReport method to display the HTML results in a browser. ExceptionsThe transform method fires .................... ..

Try {

RgObject = new repgen ();

// this method transforms the xml to html and pops up the default browser.

RgObject.buildReport (SXML, SXSLFILE);

} catch (transformerexception e) {

// see if a sourcelocator object is available. If it is, display the location

// of the error in the xml data stream. Otherwise, Just Display The Error Message.

IF (E.GETLOCATOR ()! = null) {

System.out.println ("Error In XML Document At Line"

E.GETLOCATOR (). getLinenumber () "AND color" E.GETLOCATOR (). getColumnNumber () "/ n");

} else {

System.out.println (E.getMessage ());

}

} catch (exception e) {

System.out.println (E.getMessage ());

}

If the error occurs in the XML data stream, the getLocator method in the TransformerException class allows an exception handler to determine the source of the error It returns a SourceLocator object that has two useful methods The first method -.. GetLineNumber - returns the line number of the offending node The second method -. getColumnNumber -. returns the column number where the error occurred These methods get you close to the location of the error, but I have found that it depends on the error For example,. if you forget a closing tag for one of the subnodes in the XML file, the line number overshoots to the next node's closing tag, and the column number is set to -1. Generally, the SourceLocator object returns useful information. However, most of my errors occur in the XSL template file, not the XML data stream. The SourceLocator does not locate syntax errors in XSL directives. But the TransformerException object does provide information about the location of errors in the X SOMETIMES The Error Message IS Not Very Informative. You May Get An Error Message, Such As "Identifier Must Be quote" if you forget to put double quotes around a tag "

s value. But you have to find the location of the missing double quote yourself. While the SourceLocator object is not very useful for finding XSL errors, I have found that the TransformerException generates enough information about the source of errors in XSL templates, including line numbers, to be useful in most cases. So all is not lost. in spite of these minor shortcomings, the TransformerException is quite useful for debugging XML and XSL files. Observations and SuggestionsThe Java solution is platform independent, which is a good thing. Furthermore , the RepGen object can be instantiated from a Java server page. you may want to add additional methods that return the results as a string, rather than launch a web browser to view the results. This way you can display the HTML dynamically. Also, You May Want To Compare Template File with The VALUES THAT WERE Passed To The Buildreport Method Previously in Order To Skip A Transformation That Has Already Been Done. I'll Leave these suggestions as an adercise for the reader. I '

ve noticed that the first transformation that executes takes significantly longer than the next. I attribute these results to the fact that the RepGen class and the JAXP classes are loading and compiling to native code during the first pass. If I convert the code to an Enterprise Java Bean, I suspect that this will no longer be a problem. On one real-world implementation, I compiled the code to Win32 native mode, and it ran quite well. When the transform method encounters an error in the XML data stream, the SourceLocator object can be used to return the line number and column number where the error occurred. It would have been nice if the SourceLocator object returned the source of errors in XSL template files too. When the transform method encounters an error in the XSL template file , The THE NOTS INMER IN MOSS, But You Have To Find It Yourself. The Repge n class can only be used in Java environments. If the client's platform of choice is Windows, then why not take advantage of the Microsoft MSXML 3.0 API? The next sections cover this solution in more detail. Using Microsoft's MSXML 3.0 API to Transform XML to HTML Microsoft makes the MSXML 3.0 API available for free from its download site. Go to the following URL and search with the criteria "XML." http://www.microsoft.com/downloads/search.asp You have to specify your target Operating system and "all Downloads." The Download The "MS XML Parser 3.0 Service Pack 1 Release."

This selection downloads a file called msxml3sp1.exe. Execute this file and follow the installation wizard to complete the installation. Microsoft has released a preview version of the MSXML 4.0 API, but I have not had the chance to evaluate it. The example in this article uses version 3.0 and has been tested with the original release of the MSXML 3.0 API and with service pack 1. If you like, you may download my XMLReports Browser utility, which handles the complete installation for you. If you do this, you get the MSXML3.0 API, which has been packaged with a simple browser utility that displays HTML in the MS Web Browser control. XMLReports Browser UtilityThe XMLReports Browser utility is a convenience tool that was developed to handle custom reporting in Visual Basic and ASP applications. The Xmlreports Browser Utility IS A Wrapper Object this Microsoft MSXML 3.0 API, AND Optionally Displays The Results in A Simple Browser. The user support the XML document and the XHTML / XSL template to the XMLReports Browser utility. The utility converts the documents to HTML. Using this tool, the developer can modify the layout of reports by changing the text file that contains the EXtensible HTML (XHTML) and XSLT directives. The application does not need to be recompiled every time a report changes. Your reports are built using XHTML, so you can insert images, build tables, and populate them with the data in the XML document. Many of the display characteristics of the Browser Are User-Configurable. For Example, The User May Change The Browser's Caption, The Browser '

s background colors, button images, button tool tips, and menu captions. Also, the browser object supports a WYSIWYG print function that prints all of the pages that have been inserted into the object by the client application. And you can submit multiple HTML pages to the browser object and page through them using the Next and Previous buttons. Installing the XMLReports Browser UtilityThe XMLReports Browser utility is packaged in a zip file that contains a self-extracting executable. Download the file, XMLReports.zip, at the following URL. Http://www.ftisystems.com/xmlreports.zip extract The Files Into a Temporary Directory. The Xmlreports.zip File Contains The Following Files.

setup.exe - the setup program setup.lst - the packing list that is used by the setup program XMLReports.CAB - a cabinet file that contains the XMLReports object and its dependencies XMLReports.doc -. this document Report.xml -. a sample XML file report.xsl -... a sample XHMTL file with XSLT directives Execute the setup.exe program and follow all of the directions to complete the installation If the wizard asks you if you want to keep a newer version of a file on your system, do so. do not overwrite newer versions of your files with those in the download. Hardware and Software RequirementsThe XMLReports Browser utility runs on Windows 95/98 / NT / 2000 machines. These machines must have Microsoft Internet Explorer 5.0 or higher, preferably 5.5. On machines running Windows 95, OSR2 or higher is required. On machines running Windows NT, SP3 or higher is required. XMLReports Browser Utility UsageCreate a new project in Visual Basic (VB). My example uses VB 6.0. Go to Project / References and SEL ect the "XMLReports" server. If it is not selected, click on the checkbox next to the name. If you are not using the XMLReports Browser utility, select the "Microsoft XML v3.0" server instead. The XMLReports server wraps the MSXML v3.0 Server, so you do not have to select it if you are using the XMLReports Browser utility. The XMLReports Browser utility has two methods that convert XML to HTML. One method is called InitUsingStrings and the other is called InitUsingFiles. Client applications May Call THESE METHODS REPEATEDLY IN ORDER TO GENERATE MULTIPLE Reports in The Same Browser Object. The InitusingFiles Function Converts a Client Application '

s XML document to HTML. The caller specifies an XML document filename, an XSL template filename, and an HTML filename. The following function declaration describes the InitUsingFiles method in more detail.Public Function InitUsingFiles (strXMLFile As String,

Strxslfile as string,

StrhtmlFile As string) as long

WHERE

StrxmlFile a string That Contains The Full Filespec to a File That Contains

The xml document.

Strxslfile a string That Contains The Full Filespec to a file what contains

THE XHTML AND XSL DIRECTIVES. The Template Must Conform To The Template

XSLT Namespace Uri, http://www.w3.org/1999/xsl/transform.

StrhtmlFile A String That Contains The Full Filespec to a File That Will

Contain the results of the transformation.

Return Codes:

IF NO ERROR OCCURS.

<0 if an error.

The InitUsingStrings method does the same thing as the InitUsingFiles method, except that the client application passes strings as parameters instead of filenames. Using the XMLReports Browser UtilityThe following code fragment illustrates how to use the XMLReports Browser utility in a Visual Basic application.

Dim objxmlreports as xmlreports.xmlutilities

Dim strHtmlfile As string

DIM STRXMLFILE AS STRING

DIM STRXSLFILE AS STRING

DIM LNGRESULTS AS Long

'Make Sure The Report.xml and report.xsl files are in the app.path directory.

strHtmlFile = app.path & "/report.html"

Strxmlfile = app.path & "/report.xml"

Strxslfile = app.path & "/report.xsl"

Set objxmlreports = new xmlreports.xmlutilities

LNGRESULTS = ObjxmlReports.InitusingFiles (strxmlfile, strxslfile, strhtmlfile)

If lngresults = 0 THEN

'Display The Results in The Web Browser Control.

Objxmlreports.showelse

'An error occurred. See the documentation That Comes with the

'Xmlreports Distribution for a list of the valid values ​​That Can Be Returned.

END IF

First, create an instance of the XMLReports object. Then specify the three filenames that have to be passed to the InitUsingFiles method. If the InitUsingFiles method returns zero, no error has occurred. Our example shows the browser object. A non-zero return code means that an error occurred. You will receive an error code when a file is not found by the method, when the XSL template has invalid directives in it, and when the XML data is not well-formed. If the XML data is well- formed, but the XSL template has an invalid directive, the XMLReports object creates an HTML result that shows the exact location where the error occurred in the XSL template. This handy little feature makes it easier to debug your XSL templates during the design phase. A following section will show you how to locate the source of the error in an XSL template. The XMLReports Browser Utility has a large number of properties and methods, most of which configure the look and feel of the browser object. See the doc umentation that comes with the XMLReports Browser utility for more details about these properties and methods, and for a list of error codes. Client applications do not have to display the browser object. Instead, they can execute the InitUsingStrings method to return the results of the transformation in a string. These results can be rendered with dynamic HTML in a client browser, or with Active Server Pages (ASP) scripting logic at the server. If you are going to transform XML in an Active Server Page, you probably want to use the MSXML 3.0 API directly. The next section illustrates its use. Using the MSXML 3.0 APITo use the MSXML 3.0 API, you have to build a Document Object Model (DOM) for the XML data and the XSL template source.

THEN YOUW HTML Using The XSL Template. The Following Code Fragments Show How this is done. '

'Loadxmldoc - returns the xml document object to the caller. It's buy to load

'XML and XSL Strings, Files, or Urls.

'

'On entry:

'objdomxml - the msxml2.domdocument object to load.

'varxml - if it's an xml string, loading it into the default dom document.

'IF it's a uri string, load the file or url.

'If it's an Object, Just Return IT.

'

Private sub loadxmldoc (ObjDomxml as msxml2.domdocument, variant)

DIM STRURI As String

IF INSTR (VARXML, "<")> 0 THEN

'This is a string because

Objdomxml.LoadXml VARXML

Else

'Else Load from Uri

Objdomxml.load VARXML

END IF

End Sub

'

'Transformxml: Takes The XML String OR Uri and Transforms It With The XSL String OR URI.

'

'On entry:

'VARXML - AN XML STRING, OR A URI TO AN XML File.

'varxsl - an xsl string, or a uri to an xsl file.

'

'On EXIT: a string That contacts the html.

'

Private function transformxml (VARXML As Variant, VarxSl As Variant) AS String

Dim objxml as new msxml2.domdocument

Dim objxsl as new msxml2.domdocument

ON Error Goto TransformxmlerHandler

Transformxml = ""

Loadxmldoc Objxml, VARXML

IF Objxml.Parseerror <> 0 THEN

Transformxml = makeparseError (Objxml)

EXIT FUNCTION

END IF

Loadxmldoc Objxsl, VARXSL

IF Objxsl.Parseerror <> 0 THEN

Transformxml = makeparseError (Objxsl)

EXIT FUNCTION

END IF

Transformxml = Objxml.transformNode (Objxsl)

EXIT FUNCTION

Transformxmlerhandler: TransformXML = "Error" & Err.Number & "In Transformxml. Error IS" & _

Err.Description & "."

END FUNCTION

'

'Makeparseerror: - Makes a nice html error message for display in a broment.

'

'On entry:

'Objxml - The msxml2.domdocument That Caused The Error.

'

Private function makeparseerror (Objxml as msxml2.domdocument) AS String

DIM NIDX AS INTEGER

DIM STRSPACES AS STRING

Strspaces = string (objxml.parseerror.LinePOS, "")

MakeparseError = " XML Parse Error </ Title> <body>"</p> <p>Makeparseerror = makeparseError & "<font size = 4> XML ERROR LOADING '" & _</p> <p>Objxml.parseerror.URL & "<</ font>" & _</p> <p><p> <b> <font size = 2> "& objxml.parseerror.reason & _</p> <p>"</ b> </ p> </ font>"</p> <p>If Objxml.Parseerror.Line> 0 THEN</p> <p>MakeparseError = MakeParseerror & "<p> <font size = 3> <xmp>" & _</p> <p>"AT line" & objxml.parseerror.Line & ", Character" & _</p> <p>Objxml.Parseerror.LinePos &_</p> <p>vbcrlf & objxml.parseerror.srcText &_</p> <p>VBCRLF & STRSPACES & "^" & _</p> <p>"</ xmp> </ font> </ p>"</p> <p>END IF</p> <p>Makeparseerror = makeparseerror & "</ body> </ html>"</p> <p>END FUNCTION</p> <p>The LoadXMLDoc function initializes an object of the type MSXML2.DOMDocument with the contents of the XML or XSL data stream. The data stream may be a string or a URI. Notice that the function uses different methods to initialize the object when the input source is a string, versus when the input source is a URI. The code fragment uses the loadXML method to load a string of XML or XSL directives into the document. The code fragment uses the Load method to load a URI. I am not sure why the developers of the API chose to implement the interface like this, because it requires the programmer to figure out whether the string is data or a URI. in any case, the code fragment assumes that if the string has a "<" character in it, it must be a data stream, not a URI, since this character is not a valid character for a URI. The TransformXML function calls the loadXMLDoc function. The TransformXML function has two parameters. The first parameter specifies the XML data stream or URI. The Second Par ameter specifies the XSL data stream or URI. First, the TransformXML function creates a separate instance of the MSXML2.DOMDocument object for the XML data and the XSL data. Then it calls the LoadXMLDoc function to build a DOM for each data stream. After each call, the function checks the parseError object for errors. If an error occurs, an error message is returned from the MakeParseError function. The MakeParseError function is described in the Handling errors section below. We will skip this for now. If the function successfully loads Both Data Streams, The Function Calls The XML Document '</p> <p>s transformNode method. It passes the XSL document as a parameter, so that the transformNode method can convert the XML data to HTML. The transformNode method returns an HTML string, which can be displayed in a browser. Handling ErrorsThe MSXML2.DOMDocument object returns error information in the parseError object. The default property of the parseError object is the errorCode property. It contains the last error that occurred when the document was built. If the errorCode property returns zero, no error has occurred. Otherwise, the parseError object contains more details. The following table shows the other properties and methods of the parseError object.Property or Method NameDescriptionFileposThe absolute position in the source file where the error occurred. LineThe line number in the source file where the error occurred.LineposThe column where the error occurred. Reasonthe description of the error.sourcetextthe source text of the line where the error occurred.urlthe url of the source file. The following code fragment generates an HTML page that shows the location of the error, including the source text of the line where the error occurred and a pointer to the column. The TransformXML function that is described in the previous section uses this function to Return Errors That Occurred in The LoadXmldoc function.</p> <p>'</p> <p>'Makeparseerror - Makes a nice html error message for displaying in a browser.</p> <p>'</p> <p>'On entry:</p> <p>'Objxml - The msxml2.domdocument That Caused The Error.</p> <p>'</p> <p>Private function makeparseerror (Objxml as msxml2.domdocument) AS String</p> <p>DIM NIDX AS INTEGER</p> <p>DIM STRSPACES AS STRING</p> <p>Strspaces = string (objxml.parseerror.LinePOS, "")</p> <p>Makeparseerror = "<html> <title> XML Parse Error </ Title> <body>" makeparseerror = makeparseerror & "<font size = 4> XML error Loading '" & _</p> <p>Objxml.parseerror.URL & "<</ font>" & _</p> <p><p> <b> <font size = 2> "& objxml.parseerror.reason & _</p> <p>"</ b> </ p> </ font>"</p> <p>If Objxml.Parseerror.Line> 0 THEN</p> <p>MakeparseError = MakeParseerror & "<p> <font size = 3> <xmp>" & _</p> <p>"AT line" & objxml.parseerror.Line & ", Character" & _</p> <p>Objxml.Parseerror.LinePos &_</p> <p>vbcrlf & objxml.parseerror.srcText &_</p> <p>VBCRLF & STRSPACES & "^" & _</p> <p>"</ xmp> </ font> </ p>"</p> <p>END IF</p> <p>Makeparseerror = makeparseerror & "</ body> </ html>"</p> <p>END FUNCTION</p> <p>I changed an XSL directive in my sample XSL file in order to generate an error page so that you can see how expressive it is. The following image illustrates the results after I remove a double quote from one of the tags in the XSL file. Observations and SuggestionsThe Microsoft MSXML 3.0 API only works on machines that run a version of the Windows operating system. If your client's applications are targeted to the Windows operating system, take advantage of this API. It is fast, and its XSL error locator provides decent information . Packaging the MSXML 3.0 API for deployment with your application has one drawback. The file msxml3.dll has two dependencies, both of which are missed by the Microsoft Packaging and Deployment Wizard that comes with Visual Basic 6.0. They are msxmla.dll and msxmlr .dll. THESE FILES ARE Static Dynamic Link Libraries (DLLS) AND DO NOT NEED TO BE Registered Like A Com Server Does. Nonetheless, They Are Dependencies of The Msxml3.dll, SO You Will Have to Manua lly add them to the package. Also, the Microsoft Packaging and Deployment Wizard thinks that these dependent files have to be registered like self-registering DLLs. This is not true and you will have to remove the "(DLLSelfRegister)" property for each of these files in the setup.lst manifest that gets created by the Packaging and Deployment Wizard. If you do not remove this property, the installation will display non-fatal errors to the user that require the user to click "OK"</p> <p>to continue with the installation. Conclusion If you know that your target audience is running the Windows operating system, I recommend the MSXML 3.0 API. If your audience uses machines with various operating systems, then use the Java API for XML Processing. It doesn ' t make sense to create two solutions for the same client application. Both of my solutions handled the same set of XSL directives without a problem. The subset of XSL directives that my applications require is not exhaustive. However, it does provide quite a bit of Functionality. The Following Table Contains The Xsl Directives That i Have Used in Both Environments. Many Other XSL DIRECTIVES, STRING Functions, And Math Functions Exist.</p> <p>XSL DirectiveDescription <xsl: value-of> Returns the value of the current node in an XPath <xsl: template name = "sub"> Defines a subroutine <xsl: param name = "parm1"> Defines a parameter that can be passed to A Subroutine. <XSL: Template Match = "/"> Shorthand for Matching Xpath Directives. <xsl: for-each select = "..."> for-to-next loop <xsl: call-template name = "SUB" > Calls a preproutine. <Xsl: with-param name = "..." SELECT = "..."> Passs a parameter to a subsroutine. <Xsl: if test = "..."> conditional logic - IF Test. <xsl: choose> <xsl: whentest = "..."> <xsl: OtherWise> Conditional Logic - Case Statement.EMBEDDED Functionssum () Round () Last () Position () count () Math Operators , - , * ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Information That The Parseerror Object of The MSXML 3.0 API Provides. It was easy to use, and i like this. I Was Able To Implement An Error Locator That Gen erates HTML pages, showing me exactly where the error occurred in my XML data streams and my XSL templates. This made my debugging efforts easier. Luckily, I wrote this first, so I was able to use it during my Java implementation when I had problems that were hard to diagnose. I think XML and XSLT are here to stay. The Simple Object Access Protocol (SOAP), which is an XML alternative to CORBA and DCOM, has some promise as well as. and if Microsoft .NET is as good As What I've Been Reading, in A Few Years Java Will Have Serious Competition from C </p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-29901.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="29901" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.038</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'k_2B2Y2_2FraHOFJD8x2WuZbkpMnf7aBQZT4uE7JSla4XneV7FJy5LuZHK_2BSHBy4XskwxEkDZjDen_2FDOXkAVS3MJ5w_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>