Export (0) Print
Expand All

XML Processing

 

Microsoft Corporation
October 2003

Applies to
    Microsoft® ASP.NET
    Microsoft ADO.NET
    Microsoft Internet Information Services
    Microsoft Visual Studio® .NET

Summary: Learn how Java Web applications use XML, how (or whether) the Java Language Conversion Assistant (JLCA) converts XML-related classes from Java into C# and ASP.NET, and how ASP.NET applications differ from JSP applications in their use of XML. (18 printed pages)

Contents

Introduction
XML in Java
Converting XML Code Using the JLCA
XML in .NET
Summary

Introduction

Extensible Markup Language (XML) is a simple markup language with a broad range of uses in modern Web applications. At the front end, you can use XML to make Web pages by translating XML documents (containing only marked up data) into HTML documents (containing design information) using an XSLT style sheet. They can be used as static configuration files for Web applications, such as web.xml in Java Web applications or web.config in Microsoft® ASP.NET. XML is also an ideal method of data transfer between platforms and languages because of its simple, universally readable structure.

In this white paper, we will start by looking at how Java Web applications leverage XML using various APIs. We will then examine how (or whether) the Java Language Conversion Assistant (JLCA) converts XML-related classes from Java into C# and ASP.NET. Finally, we'll look at how ASP.NET applications differ from JSP applications in their use of XML.

XML in Java

In Java, XML is handled through two different APIs: Simple API for XML (SAX), and the Document Object Model (DOM). Each of these allows you to process an XML document and do something with its elements and attributes, but in very different ways.

SAX

SAX is an event-based API, which means that it reports results back to the application (or calls back) as the XML file is parsed. Conceptually, SAX parsers break an XML file into pieces, starting from the beginning of the file, notifying your application after each piece has been parsed. This differs from the DOM, which parses an XML file completely and then presents your application with a complete node tree. SAX gives your application the opportunity to store only the information it needs as the parse progresses and to discard the rest.

The following example parses an XML document (hello.xml) and displays the content as text in a Web browser. As the SAX parser reads the document, it issues calls back to the program (or launches events) every time it encounters something interesting, such as an XML tag. The program then traps the events and performs an action (such as writing the tag contents to the screen).

The example consists of three parts: a handler class to trap the events SAX will call as it parses the document (Handler.java); a JSP file (hello.jsp) that will implement the handler, parse the document, and output the results as HTML; and a sample XML file (hello.xml).

Note that the example requires sax2r2.jar, which you can download from saxproject.org. You need to add this JAR to your CLASSPATH so that the appropriate SAX classes can be found. In addition, you will also need to have an XML parser, such as Xerces, installed and in your CLASSPATH.

Listing 1. Handler.java

package codenotes;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class Handler extends DefaultHandler {

   // A string in which we store the output for later use in the JSP
   private String output ="";
   // A helper method that returns the completed output from the handler
   public String getOutput() { return output; }

   // SAX calls this method when it encounters an element
   public void startElement(String strNamespaceURI, String strLocalName,
      String strQName, Attributes al) throws SAXException {
         output = output + "startElement: " + strQName + "<br>";
   }

   /* SAX calls this method to pass in character data stored
   between the start and end tags of a particular element */
   public void characters(char[] a, int s, int l) throws SAXException {
      output = output + "characters: " + new String(a, s, l) + "<br>";
   }

   /* SAX calls this method when the end-tag for an
   element is encountered */
   public void endElement(String strNamespaceURI, String strLocalName,
      String strQName) throws SAXException {

      output = output + "endElement: /" + strQName + "<br>";
   }
}

Note that the handler class (Handler.java) traps three events: the start of a tag, character data, and the end of a tag. The tag events (startElement() and endElement()) will print the name of the tag to the screen, while the characters() event will print the tag content to the screen.

The next part of the application, hello.jsp, creates a new instance of the handler class, a SAX parser, parses an XML file named hello.xml, and then outputs the results as HTML.

Listing 2. hello.jsp

<%@ page import="codenotes.Handler,
   org.xml.sax.*,
   org.xml.sax.helpers.*,
   javax.xml.parsers.*"
%>

<%
   // create a handler
   Handler handler = new Handler();

   // create a parser
   SAXParserFactory spf = SAXParserFactory.newInstance();
   XMLReader parser = null;
   SAXParser saxParser = spf.newSAXParser();
   parser = saxParser.getXMLReader();

   // assign the handler to the parser
   parser.setContentHandler (handler);

   // parse the document
   parser.parse("C:/cnmig/xmlsax/xml/hello.xml");

%>

<html>
   <body>
      <p><%= handler.getOutput() %></p>
   </body>
</html>

Notice how we need to import our handler class as well as three sets of support classes needed to parse the XML document. Now, suppose hello.xml looks like Listing 3.

Listing 3. hello.xml

<?xml version="1.0"?>
<name>Craig Wills</name>

The output from hello.jsp would then look like Listing 4.

Listing 4. Output from hello.jsp

startElement: name
characters: Craig Wills
endElement: /name

SAX parsers make callbacks to the application through a set of interfaces, most importantly ContentHandler. These interfaces are implemented by a handler class, either directly or through the use of the DefaultHandler adapter class. The various methods within the handler process different fragments of XML (start-tags, character data, and so on) as the parse progresses. The totals, lists, or other data structures that your application builds during these callbacks become the end result of your processing.

DOM

The Document Object Model (DOM) is a W3C standard for reading and manipulating XML data. As with SAX, you can choose from various parser implementations of DOM (with corresponding APIs). Regardless of which DOM parser you choose, DOM presents an XML document as a tree of nodes, where each node represents an element, attribute, or text data. The tree structure that the DOM creates will always correspond to the hierarchical structure of the XML document it is used to parse. The root element (or node) sits on the first level of the tree, its children on the next level, and so on. The DOM provides random access to any of these nodes, which means that you can read or change any part of the document at any time.

The following example requires the XML document in Listing 5, hello.xml.

Listing 5. hello.xml

<?xml version="1.0"?>
<display>Hello World!</display>

Note that the example requires that you have a DOM parser installed. If you have an XML parser such as Xerces installed, you will most likely not need anything else to parse DOM documents. If you don't, we suggest you download the Java API for XML Processing (JAXP).

The hello.jsp application in Listing 6 loads hello.xml into memory using the DOM, and outputs the contents of the <display> element as HTML.

Listing 6. hello.jsp using the DOM

<%@ page
   import="javax.xml.parsers.*, org.w3c.dom.*"
%>

<%
   // load and parse the document
   DocumentBuilder builder;
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   builder = factory.newDocumentBuilder();
   Document document = builder.parse("C:/cnmig/xmldom/xml/hello.xml");

   // retrieve and display Hello World!
   Element root = document.getDocumentElement();
   Node text = root.getFirstChild();
%>

<html>
   <body>
      <p><%=text.getNodeValue() %></p>
   </body>
</html>

The output from hello.jsp is shown in Listing 7.

Listing 7. Output of hello.jsp, from Listing 6

Hello World!

DOM's main disadvantage is that it loads an entire document into memory. If you are working with especially large documents, or only require fast, one-pass access to the contents of an XML document, you should instead investigate using SAX as an alternative. SAX-based programs process an XML document by working with small fragments one at a time (an element, some text, and so on); as a result, they tend to be much faster and less memory-intensive than the DOM-based applications.

XML on the CodeNotes Web Site

The CodeNotes Web site stores the text of CodeNotes pointer articles as XML documents in a Microsoft SQL Server™ database. When an article is requested for the first time, a call is made to the database to extract the appropriate XML document. The document is then transformed into HTML using an XSLT style sheet, and displayed to the user in his or her browser.

For example, Listing 8 shows a chunk of XML from the beginning of CodeNotes pointer XM050089.

Listing 8. A fragment from XM050089

<?xml version="1.0"
encoding="UTF-8"?>

<article><articleHeader><CNPointer>XM000589</CNPointer>
<articleTitle>Using XSLT to Create BCP CSV and Format Files</articleTitle>
<authors><author>Brent Williams</author></authors>
<book>CodeNotes for XML</book>
<articleDescription>This article demonstrates using XSLT to output
text files (as opposed to the usual HTML or XML files).
</articleDescription></articleHeader>
<articleBody><p>This example demonstrates using XSLT to output text
files (as opposed to the usual HTML or XML files). Assume we have
been given the following set of XMLrecords and their schema and wish
to store them in a database. Most relational databases support some
kind of text-based import utility for just this purpose. In this
example, we will transform the above XML files into two data files
suitable for use with Microsoft SQL Server's command-line BCP (Bulk
Copy Program) utility. We will have to convert the input XML into a
comma-delimited DAT file, and an input XML schema into a space-
delimited FMT file. The XML input file appears as follows:</p>
...

Listing 9 shows the section of CNArticle.xsl that handles the elements shown in Listing 8 (<article>, <articleHeader>, and so on).

Listing 9. A fragment of CNArticle.xsl

xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:output method="html" indent="yes"/>
<xsl:param name="imageDirectory"></xsl:param>

<!-- article -->

<xsl:template match="article"> 
   <xsl:apply-templates select="articleHeader" />
   <xsl:apply-templates select="articleBody" />
</xsl:template>

<!-- articleHeader -->
<xsl:template match="articleHeader">
   <h1><xsl:apply-templates
      select="CNPointer"/> - <xsl:apply-templates
      select="articleTitle"/></h1>
   <h4>Article Author:
      <xsl:apply-templates select="authors/author"/><BR/>
      From Book: <xsl:apply-templates
         select="book"/><BR/>
      Date Published:
      <xsl:apply-templates select="publishedDate"/>
   </h4>
</xsl:template>

<!-- articleBody -->
<xsl:template match="articleBody">
   <xsl:apply-templates/>
</xsl:template>

<!-- p -->
<xsl:template match="p">
   <p><xsl:apply-templates/></p>
</xsl:template>

Finally, Listing 10 shows the resulting HTML that will be displayed in the content section of the Article Display page.

Listing 10. Resulting HTML after XSLT processing

<h1>XM000589 - Using XSLT to Create BCP CSV and Format Files</h1>
<h4>Article Author: Brent Williams<BR>
   From Book: CodeNotes for XML<BR>
   Date Published: March 12, 2003</h4>
<p>This example demonstrates using XSLT to output text
files (as opposed to the usual HTML or XML files). Assume we have
been given the following set of XML records and their schema and
wish to store them in a database. Most relational databases support
some kind of text-based import utility for just this purpose. In
this example, we will transform the above XML files into two data
files suitable for use with Microsoft SQL Server's command-line
BCP (Bulk Copy Program) utility. We will have to convert the input
XML into a comma-delimited DAT file, and an input XML schema into
a space-delimited FMT file. The XML input file appears as follows:</p>

Note that this HTML is also formatted for appearance using a .css (cascading style sheet) file that is referenced earlier in the HTML page.

Converting XML Code Using the JLCA

Most Java code that deals with XML does not convert using the JLCA. This is either because XML code is part of the javax library, which is not included in the "true" Java classes, or because the XML classes you are using are part of an entirely separate package (such as the SAX package we used in the previous section), and therefore the JLCA cannot be expected to handle them.

For example, Listing 11 shows the result of converting hello.jsp to hello.aspx using the JLCA.

Listing 11. Results of converting hello.jsp to ASP.NET

<%@ Page language="c#"
   CodeBehind="hello.aspx.cs" Inherits="xmlsax.hello"
   AutoEventWireup="false"%>
<%@ Import Namespace="Handler=codenotes.Handler"%>

<%
   // create a handler
   Handler handler = new Handler();

   // create a parser
   //UPGRADE_TODO: Class
      'javax.xml.parsers.SAXParserFactory' was not converted.
   ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"
   //UPGRADE_TODO: Method
      'javax.xml.parsers.SAXParserFactory.newInstance' was not converted.
   ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"
   SAXParserFactory spf = SAXParserFactory.newInstance();
   //UPGRADE_TODO: Interface
      'org.xml.sax.XMLReader' was not converted.
   ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"
   XMLReader parser = null;
   //UPGRADE_TODO: Class
      'javax.xml.parsers.SAXParser' was not converted.
   ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"
   //UPGRADE_TODO: Method
      'javax.xml.parsers.SAXParserFactory.newSAXParser' was not converted.
   ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"
   SAXParser saxParser = spf.newSAXParser();
   //UPGRADE_TODO: Method
      'javax.xml.parsers.SAXParser.getXMLReader' was not converted.
   ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"
   parser = saxParser.getXMLReader();

   // assign the handler to the parser
   //UPGRADE_TODO: Method
      'org.xml.sax.XMLReader.setContentHandler' was not converted.
   ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"
   parser.setContentHandler(handler);

   // parse the document
   //UPGRADE_TODO: Method
      'org.xml.sax.XMLReader.parse' was not converted.
   ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"
   parser.parse("C:/cnmig/xmlsax/xml/hello.xml");

%>

<html>
   <body>
      <p><%=handler.Output%></p>
   </body>
</html>

As you can see, most of the lines dealing with XML-related or SAX-related classes did not convert at all. The JLCA simply left them as they were, and indicated that something needed to be changed with an UPGRADE_TODO message. You will get similar results if you try converting the DOM code from Listing 6.

The solution to this problem is, unfortunately, that you have to manually convert all of your XML code to ASP.NET-friendly code. As we'll see in the next section, DOM code in C# is very similar to Java and will not require many changes. SAX code, however, is entirely different, as .NET uses a proprietary XMLReader model that does not follow the SAX standard (although it functions similarly).

XML in .NET

.NET provides built-in support for many of the core technologies surrounding XML, including SAX, DOM, XSLT, XPath, and XML Schemas. In this section, we'll look at how you can take advantage of this support in your Web applications, and how you can move from JSP to ASP.NET by replacing Java-style XML code with .NET-style XML code.

.NET XML Namespaces

As with all other .NET classes, .NET classes are divided into a series of namespaces, each one dealing with a different XML technology. The primary namespaces are as follows:

  • System.Xml provides most of the basic XML functionality, including necessary classes and methods for using DOM and XMLReader (Microsoft's equivalent of SAX). Note that the intro for the System.Xml namespace page in the class library is misleading, as this namespace does not actually provide support for Schemas, XPath, or XSLT.
  • System.Xml.Xsl provides support for XSL documents and transformations.
  • System.Xml.XPath provides support for XPath, a simple query language for XML.
  • System.Xml.Schema provides support for XML Schemas, which are used to define templates for XML documents. If you are familiar with Document Type Definitions (DTDs), XML Schemas are similar except that they are themselves written in XML, and allow much more diverse templating.
  • System.Xml.Serialization provides classes for serializing objects into XML format for things like data transfer.

Note that these classes are not hierarchical. Including System.Xml in your application does not mean that you have included all the rest of the XML classes as well. You need to import each one individually.

DOM in .NET

DOM code in .NET is very similar to DOM code in Java. Both provide fairly strict implementations of the W3C DOM specification; .NET supports the DOM Level 1 Core and DOM Level 2 Core specifications. This means that translating your Java XML applications into .NET will be fairly straightforward.

There are two main differences between DOM in Java and .NET that will be immediately apparent.

Loading an XML Document

Loading an XML document into your application using the DOM is much more straightforward in .NET than in Java. Listing 12 shows the two lines of code required to do this.

Listing 12. Loading an XML document using the DOM

XmlDocument myXMLDoc = new XMLDocument();
myXMLDoc.load("myXMLFileName.xml");

The first line of code creates an XmlDocument object that will be used as a reference to the XML file. The empty constructor is the only one available.

The second line loads a reference to the XML document myXMLFileName.xml. The load() method is actually overloaded, and will accept any of the following parameter types:

  • A String representing the name of the file. If there is an error loading or parsing the file, an XmlException will be thrown and the document will remain empty.
  • Any Stream subclass type representing the source of the XML file.
  • A TextReader representing the source of the XML file.
  • An XmlReader. This parameter allows you to validated the XML document during loading; we'll look at an example of using XmlReader later in this section.

Methods replaced by properties

Many method calls in Java DOM have been replaced by properties in .NET DOM. This generally won't be much of a problem, as you will simply need to remove the brackets at the end of the Java method calls in order to have them work in .NET. If you pay attention to your Microsoft Intellisense®, the instances where methods have changed to properties will be obvious.

Manually converting Java DOM to .NET

The best way to manually convert your Java DOM code into .NET DOM code depends on the way you use XML in your class.

If you have only one or two XML-related objects and repeatedly reassign them, it is probably easier to catch the problems at compile time. Simply compile and run the program, and make use of the task list generated by the errors to fix individual instances where the code did not convert. In most cases, it will simply be a matter of removing brackets from the names of methods that have become properties.

If you have many objects, a complete rewrite of the code might be the way to go. The best way to do this is to print out your original Java file and rewrite the code in C# using the same pattern. The logic doesn't change, and this should take you at most 10 or 15 minutes for most classes.

Microsoft extensions to the DOM

Outputting a DOM document in Java is somewhat involved. You can either use a Transformer class as a conduit to a stream, or design your own DOM writer class to output XML using the DOM. The latter is what we use on the CodeNotes Web site.

Microsoft, however, provides proprietary extensions to its XmlDocument class that allow you to output DOM documents quickly and easily. The most common of these methods are as follows:

  • XmlDocument.Save() saves an XML document to a specified location. This location can be a stream, a file, a TextWriter, or an XmlWriter.
  • XmlDocument.WriteTo() saves an XmlDocument node to a specified XmlWriter.
  • XmlDocument.WriteContentTo() saves all children of an XmlDocument node to a specified XmlWriter.

In addition to these output classes, Microsoft has also scattered proprietary extensions throughout its implementation of the DOM. For more information on these, please see the MSDN® Library.

A conversion example from the CodeNotes Web site

The following is a method that can be found in Context.java, a support class used to maintain context during a user's visit to the CodeNotes Web site. It uses the DOM to parse an XML document containing a list of available code samples relating to the CodeNotes books.

Listing 13. Using DOM in the Java version of codenotes.com (Context.java)

public Document
getCodeSamplesDocument()
{
   if ( codeSamplesDoc==null )
   {
      // load code
      try
      {
         DOMParser parser = new DOMParser();
         String confFile = configFile.getProperty("code.xmlFile");
         String xmlFileName = (new File(codenotesHome,
(configFile.getProperty("code.home")))).getCanonicalPath()+File.separator+
  confFile;
          parser.parse(xmlFileName);
          codeSamplesDoc = parser.getDocument();
      } catch ( Exception ex ) {
         System.out.println("Error! 
            Unable to read CodeSamples config file " +ex);
      }
   }
   return codeSamplesDoc;
}

When this method is converted to .NET, the JLCA changes it into a property, as it is a method that begins with "get" and has no parameters. Although all the internal code of this method had to be changed manually, you can see in Listing 14 that the basic logic and even most of the method names are very similar.

Listing 14. Using DOM in the .NET version of codenotes.com (Context.java)

virtual public XmlDocument
CodeSamplesDocument
{
   get
   {
      if (codeSamplesDoc == null)
      {
         // load code
         try
         {
            codeSamplesDoc = new XmlDocument();
            String confFile = configFile.getProperty("code.xmlFile");
            String xmlFileName = (new
               FileInfo(codenotesHome.FullName + "\\" +

               (configFile.getProperty("code.home")))).FullName +

                Path.DirectorySeparatorChar.ToString() + confFile;
             codeSamplesDoc.Load(xmlFileName);
         }
         catch (System.Exception ex)
         {

            System.Console.Out.WriteLine("Error! 
               Unable to read CodeSamples config file " + ex);
         }
      }
      return codeSamplesDoc;
   }
}

This property can then be accessed as Context.CodeSamplesDocument instead of Context.getCodeSamplesDocument() (from Java).

SAX in .NET

.NET uses a proprietary class called XmlReader instead of SAX. The two are very similar, and would be used in similar circumstances, but are not based on the same API. Both of them read XML documents from start to finish, one piece at a time. The main difference between SAX and XmlReader is in how the parsers handle the pieces as they get them.

SAX works on a "push" model. The parser reads through the XML document, and sends messages to a handler class that must do something with them. XmlReader, however, uses a "pull" model. The class requests pieces from the reader at its own pace, only when it needs them. When it needs the next piece, it must "ask" for it, rather than simply receiving it automatically.

XmlReader is an abstract class, and you will generally work with one of its implementations. XmlValidatingReader automatically validates against a DTD or schema if one is available), whereas SAX only allows validation against DTDs. If you don't need validation, XmlTextReader is probably the best choice; it simply reads forward through an XML document and has methods that return data on content and node types.

The end result of these differences is that, as with the DOM, SAX-style processing in .NET is much faster and easier to implement. The code has been simplified and hidden "under the hood" to such an extent that nowhere near the amount of developer-designed code is needed to load and parse documents using XmlReader.

Using an XmlReader

The code in Listing 15 demonstrates the use of a simple XmlTextReader. This code simply parses through an XML document, and each time it encounters a <name> element, it prints the character content of that element.

Listing 15. Using XmlReader

<%@ Page language="c#"
   CodeBehind="hello.aspx.cs"
   Inherits="xmlsax.hello" AutoEventWireup="false"%>
<%@ Import namespace="System.Xml" %>
<html>
   <%
      XmlTextReader myReader = new
      XmlTextReader("C:/cnmig/xmlsaxConv/xml/hello2.xml");
   %>
   <body>
   <% while (myReader.Read()) {
      if
         (myReader.Name.Equals("name")) {
         myReader.Read(); %>
         <p><%=
         myReader.Value %></p>
      <% }
   } %>
   </body>
</html>

<% myReader.Close(); %>

Using a validating parser like XmlValidatingReader is similar, except that you specify a DTD or XSLT document when you create the reader instance.

Manually Converting javax.xml.transform to System.Xml.Xsl

In the first section of this white paper, we looked at an example of how XML is used on the CodeNotes Web site. Articles are stored in a database as XML. When requested, the XML is extracted from the database, transformed into HTML using an XSLT stylesheet, and then displayed on the articles page.

A simplified example of how this conversion is done in Java can be seen in Listing 16. Note that before the code will work you would need to set up a TransformerFactory implementation using your system properties, or rely on your J2SE to have one (most of them do).

Listing 16. Transforming XML using XSLT in Java

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xsl));
transformer.transform(new StreamSource(in), new StreamResult(out));

xsl and in are InputStream objects representing the XSL style sheet and original XML document. out is an OutputStream representing the resultant document. StreamSource is a javax.xml.transform object.

In .NET, you would replace the code in Listing 16 with Listing 17.

Listing 17. Transforming XML using XSLT in .NET

XslTransform transformer = new XslTransform();
transformer.Load(new XPathDocument(xsl), null, null);
XPathDocument doc = new XPathDocument(inStream);
transformer.Transform(doc, null, outStream, null);

Both implementations also allow you to pass in additional arguments for the conversion that act as parameters or extension objects. In java, this is done in the following manner:

Listing 18. Passing in additional arguments for conversion in Java

// params is a Hashtable
// this code would be inserted between the Transformer
transfoer = tFactory 
// Line in the previous java sample
Enumeration enum=params.keys();
while ( enum.hasMoreElements() )
{
   String key=((String)enum.nextElement());
   String value=((String)params.get(key));
   transformer.setParameter(key,value);
}

Listing 19 shows the equivalent code in .NET.

Listing 19. Passing in additional arguments for conversion in .NET

// xslParams is a HashTable
// This code would be inserted just after the doc object is initialized.
XsltArgumentList xslArgs = new XsltArgumentList();
IDictionaryEnumerator hashEnum = xslParams.GetEnumerator();
while (hashEnum.MoveNext())
{
   xslArgs.AddParam(hashEnum.Key.ToString(), "",
      hashEnum.Value.ToString());
} // while
transformer.Transform(doc, xslArgs, outStream, null);

As you can see, the logic and methodology for transforming XML in Java and .NET is very similar. Even though the JLCA will not convert such code directly, you should easily be able to convert it manually using the patterns shown above.

Summary

Unfortunately, the JLCA does not provide support for the conversion of XML-related classes from Java to .NET. Fortunately, the two different ways in which you can interact with XML in Java, DOM and SAX, are also available in .NET. You will just need to do most of the conversion manually.

Conversion of DOM code is often as simple as removing brackets from Java methods that have become properties in .NET. Most of the classes and methods have parallels with identical or similar names, and you simply need to go through each one and change it by hand. Often, the easiest way to do this is simply to run the program and then attend to the errors in the task list one at a time.

SAX-style XML processing is handled by the XmlReader class in .NET. XmlReader differs from SAX in that it follows a pull model (classes must request XML fragments from the parser) instead of a push model (parser sends out fragments that must be intercepted and handled by a class). In addition, XmlReader supports XML Schemas as well as DTDs, whereas most SAX processors do not.

In the end, coding both DOM- and SAX-style XML applications is generally easier and more streamlined in Microsoft .NET.

Show:
© 2014 Microsoft