DocumentBuilderFactory and TransformerFactory

I saw some coding like this:*
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("encoding","UTF-8");
t.transform(new DOMSource(doc),new StreamResult(baos)); String xmlString = new String(baos.toByteArray(), "utf8");
My questions are:*
1) Does the doc (Document)
contains the such header as:
*<?xml version="1.0" ?>*
2) Must the doc object host an XML string, or it can contain any type string(i.e., not necessarily an XML string)?
3) What is the purpose of using the transformer to transform the doc as:
t.transform(new DOMSource(*doc*),new StreamResult(*baos*));
4) Does the Transformer add the header <?xml version="1.0" ?> to the baos object?
Thanks
Scott
Edited by: scottjsn on Jan 11, 2008 3:58 PM

I saw some coding like this:*
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("encoding","UTF-8");
t.transform(new DOMSource(doc),new StreamResult(baos)); String xmlString = new String(baos.toByteArray(), "utf8");
My questions are:*
1) Does the doc (Document)
contains the such header as:
*<?xml version="1.0" ?>*
2) Must the doc object host an XML string, or it can contain any type string(i.e., not necessarily an XML string)?
3) What is the purpose of using the transformer to transform the doc as:
t.transform(new DOMSource(*doc*),new StreamResult(*baos*));
4) Does the Transformer add the header <?xml version="1.0" ?> to the baos object?
Thanks
Scott
Edited by: scottjsn on Jan 11, 2008 3:58 PM

Similar Messages

  • DocumentBuilderFactory and my applet

    I am creating an applet that will read an XML file and parse the file to grab some info. I created the project in netbeans and i'm using the java.xml.parsers.DocumentBuilder and java.xml.parsers.DocumentBuilderFactory classes to do the work. When i run the applet and the config file is found it is read in just fine in the browser but i get a dozen errors in my server log saying "No route matches "/META-INF/services/javax.xml.parsers.DocumentBuilderFactory" with {:method=>:get}". This is bad because it makes the web app think an error occurred and it will spam our error email address. Is there something wrong with how i'm creating my applet or is this an issue with the web application?
    Thank you,
    Austin

    Appetviewer fails on my applet:
    runrun sun.applet.Main Pancet.class
    Set uncaught java.lang.Throwable
    Set deferred uncaught java.lang.Throwable
    >
    VM Started:
    The application exited
    yet it ran fine when I created it in JBuilder. Does
    appletviewer require a "main" method? No.
    My applet does
    implement "runnable". Does the fact that I haven't
    yet coaxed Mozilla into accepting the latest java
    plugin have barring on the problem (this would seem
    unlikely to me)? No, don't think so. Sounds like an uncaught exception to me. Maybe a security exception? What's the applet doing?

  • XML Parse issues when using Network Data Model LOD with Springframework 3

    Hello,
    I am having issues with using using NDM in conjuction with Spring 3. The problem is that there is a dependency on the ConfigManager class in that it has to use Oracle's xml parser from xmlparserv2.jar, and this parser seems to have a history of problems with parsing Spring schemas.
    My setup is as follows:
    Spring Version: 3.0.1
    Oracle: 11GR2 and corresponding spatial libraries
    Note that when using the xerces parser, there is no issue here. It only while using Oracle's specific parser which appears to be hard-coded into the ConfigManager. Spring fortunately offers a workaround, where I can force it to use a specific parser when loading the spring configuration as follows:
    -Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl But this is an extra deployment task we'd rather not have. Note that this issue has been brought up before in relation to OC4J. See the following link:
    How to change the defaut xmlparser on OC4J Standalone 10.1.3.4 for Spring 3
    My question is, is there any other way to configure LOD where it won't have the dependency on the oracle parser?
    Also, fyi, here is the exception that is occurring as well as the header for my spring file.
    org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:
    Line 11 in XML document from URL [file:/C:/projects/lrs_network_domain/service/target/classes/META-INF/spring.xml] is invalid;
    nested exception is oracle.xml.parser.schema.XSDException: Duplicated definition for: 'identifiedType'
         at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
         [snip]
         ... 31 more
    Caused by: oracle.xml.parser.schema.XSDException: Duplicated definition for: 'identifiedType'
         at oracle.xml.parser.v2.XMLError.flushErrorHandler(XMLError.java:425)
         at oracle.xml.parser.v2.XMLError.flushErrors1(XMLError.java:287)
         at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:331)
         at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:222)
         at oracle.xml.jaxp.JXDocumentBuilder.parse(JXDocumentBuilder.java:155)
         at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
         at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)Here is my the header for my spring configuration file:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">Thanks, Tom

    I ran into this exact issue while trying to get hibernate and spring working with an oracle XMLType column, and found a better solution than to use JVM arguments as you mentioned.
    Why is it happening?
    The xmlparserv2.jar uses the JAR Services API (Service Provider Mechanism) to change the default javax.xml classes used for the SAXParserFactory, DocumentBuilderFactory and TransformerFactory.
    How did it happen?
    The javax.xml.parsers.FactoryFinder looks for custom implementations by checking for, in this order, environment variables, %JAVA_HOME%/lib/jaxp.properties, then for config files under META-INF/services on the classpath, before using the default implementations included with the JDK (com.sun.org.*).
    Inside xmlparserv2.jar exists a META-INF/services directory, which the javax.xml.parsers.FactoryFinder class picks up and uses:
    META-INF/services/javax.xml.parsers.DocumentBuilderFactory (which defines oracle.xml.jaxp.JXDocumentBuilderFactory as the default)
    META-INF/services/javax.xml.parsers.SAXParserFactory (which defines oracle.xml.jaxp.JXSAXParserFactory as the default)
    META-INF/services/javax.xml.transform.TransformerFactory (which defines oracle.xml.jaxp.JXSAXTransformerFactory as the default)
    Solution?
    Switch all 3 back, otherwise you'll see weird errors.  javax.xml.parsers.* fix the visible errors, while the javax.xml.transform.* fixes more subtle XML parsing (in my case, with apache commons configuration reading/writing).
    QUICK SOLUTION to solve the application server startup errors:
    JVM Arguments (not great)
    To override the changes made by xmlparserv2.jar, add the following JVM properties to your application server startup arguments.  The java.xml.parsers.FactoryFinder logic will check environment variables first.
    -Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl -Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl -Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
    However, if you run test cases using @RunWith(SpringJUnit4ClassRunner.class) or similar, you will still experience the error.
    BETTER SOLUTION to the application server startup errors AND test case errors:
    Option 1: Use JVM arguments for the app server and @BeforeClass statements for your test cases.
    System.setProperty("javax.xml.parsers.DocumentBuilderFactory","com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
    System.setProperty("javax.xml.parsers.SAXParserFactory","com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
    System.setProperty("javax.xml.transform.TransformerFactory","com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
    If you have a lot of test cases, this becomes painful.
    Option 2: Create your own Service Provider definition files in the compile/runtime classpath for your project, which will override those included in xmlparserv2.jar.
    In a maven spring project, override the xmlparserv2.jar settings by creating the following files in the %PROJECT_HOME%/src/main/resources directory:
    %PROJECT_HOME%/src/main/resources/META-INF/services/javax.xml.parsers.DocumentBuilderFactory (which defines com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl as the default)
    %PROJECT_HOME%/src/main/resources/META-INF/services/javax.xml.parsers.SAXParserFactory (which defines com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl as the default)
    %PROJECT_HOME%/src/main/resources/META-INF/services/javax.xml.transform.TransformerFactory (which defines com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl as the default)
    These files are referenced by both the application server (no JVM arguments required), and solves any unit test issues without requiring any code changes.
    This is a snippet of my longer solution for how to get hibernate and spring to work with an oracle XMLType column, found on stackoverflow.

  • [Solution] DocumentBuilderFactory, Serialization, and WL 8.1 SP 2

    <pre>
    Hello All!
    I finally have gotten my web services to work properly. All of my serialization
    woes were caused by my using the javax.xml.parsers.DocumentBuilderFactory and
    NOT setting the following options:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);
    Yup. That's it. I saw this being done in one of the tech support people's examples:
    private Document getDocumentWithWL(String resourceName)
    throws Exception
    weblogic.apache.xerces.parsers.DOMParser parser = new weblogic.apache.xerces.parsers.DOMParser();
    parser.setFeature(
    "http://apache.org/xml/features/dom/defer-node-expansion",
    false );
    parser.setFeature( "http://xml.org/sax/features/validation",
    false);
    parser.setFeature( "http://xml.org/sax/features/namespaces",
    true);
    parser.setFeature( "http://apache.org/xml/features/validation/schema",
    true);
    parser.parse(new org.xml.sax.InputSource(this.getClass().getClassLoader().getResourceAsStream(resourceName)));
    return(parser.getDocument());
    and decided to write the analog to this using the DocumentBuilderFactory:
    private Document getDocumentWithDB(String resourceName)
    throws Exception
    DocumentBuilder db = null;
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    // Set params
    fac.setValidating(false);
    fac.setNamespaceAware(true);
    db = fac.newDocumentBuilder();
    Document doc = db.parse(this.getClass().getClassLoader().getResourceAsStream(resourceName));
    return(doc);
    Now my doc/lit web services are able to marshall data between the service and
    client. I have to still use the DII dynamic proxy client method for invoking
    the web service (SOAPElement!! grr).
    Thanks to all who helped diagnose this problem. You know that you have this problem
    when you see errors about "Local name of attribute can not be null ...." coming
    out of weblogic's XML serialization code.
    Hope this helps someone else out there
    -- jake
    </pre>

    Well basically that means there was a partial message that came in over a socket, and the server waited 60 seconds for the rest of the message, but it never arrived.
    Was the server, or a client under heavy load? Did you notice any response time problems?
    -- Rob
    WLS Blog http://dev2dev.bea.com/blog/rwoollen/

  • Can someone explain why one code works and the other one doesn't?

    Hi,
    I have been doing a little work with XML today and I wrote the following code which did not function properly. In short, it was as if there were elements in the NodeList that disappeared after the initial call to NodeList.getElementsByTagName("span"); The code completely drops through the for loop when I make a call to getTextContent, even though it is not a controlling variable and it does not throw an exception! I'm befuddled. The second portion of code works. For what it is worth, tidy is the HTML cleaner that's been ported to java (JTidy) and parseDOM(InputStream, OutputStream) is supposed to return a Document, which it does! So why I have to call a DocumentBuilderFactory and then get a DocumentBuilder is beyond me. If I don't call Node.getTextContent() the list is processed properly and calls to toString() indicate that the class nodes are in the list! Any help would be appreciated!
    import com.boeing.ict.pdemo.io.NullOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.util.Properties;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.tidy.Tidy;
    public class HTMLDocumentProcessor {
        // class fields
        private Properties tidyProperties   = null;
        private final String tidyConfigFile =
                "com/boeing/ict/pdemo/resources/TidyConfiguration.properties";
         * Creates a new instance of HTMLDocumentProcessor
        public HTMLDocumentProcessor() {
            initComponents();
        private void initComponents() {
            try {
                tidyProperties = new Properties();
                tidyProperties.load(ClassLoader.getSystemResourceAsStream(tidyConfigFile));
            } catch (IOException ignore) {
        public Document cleanPage(InputStream docStream) throws IOException {
            Document doc = null;
            NullOutputStream nos = new NullOutputStream(); // A NullOutputStream is
                                                           // is used to keep all the
                                                           // error output from printing
            // check to see if we were successful at loading properties
            if (tidyProperties.isEmpty()) {
                System.err.println("Unable to load configuration file for Tidy");
                System.err.println("Proceeding with default configuration");
            Tidy tidy = new Tidy();
            // set some local, non-destructive settings
            tidy.setQuiet(true);
            tidy.setErrout(new PrintWriter(nos));
            tidy.setConfigurationFromProps(tidyProperties);
            doc = tidy.parseDOM(docStream, nos);
            // assuming everything has gone ok, we return the root element
            return doc;
        public static void main(String[] args) {
            try {
                String fileName = "C:/tmp/metars-search.htm";
                File htmlFile = new File(fileName);
                if (!htmlFile.exists()) {
                    System.err.println("File : " + fileName + " does not exist for reading");
                    System.exit(0);
                FileInputStream fis = new FileInputStream(htmlFile);
                HTMLDocumentProcessor processor = new HTMLDocumentProcessor();
                Document doc = processor.cleanPage(fis);
                if (doc == null) {
                   System.out.println("cleanPage(InputStream) returned null Document");
                   System.exit(0);
                NodeList spanTags = doc.getElementsByTagName("span");
                int numSpanTags = spanTags.getLength();
                System.out.println("Number of <span> tags = " + numSpanTags);
                for (int i = 0; i < numSpanTags; i++) { // Loop falls through here!
                    System.out.println("Span tag (" + i + ") = " +
                                        spanTags.item(i).getTextContent());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.exit(0);
    }This segment of code works!
    import com.boeing.ict.pdemo.io.NullOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.util.Properties;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.tidy.Tidy;
    import org.xml.sax.SAXException;
    * Class designed to remove specific notam entries from the
    * HTML document returned in a request. The document will contain
    * either formatted (HTML with CSS) or raw (HTML, pre tags). The
    * Formatted HTML will extract the paragraph body information from the
    * document in it's formatted state. The raw format will extract data
    * as simple lines of text.
    * @author John M. Resler (Capt. USAF, Ret.)<br/>
    * Class : NotamExtractor<br/>
    * Compiler : Sun J2SE version 1.5.0_06<br/>
    * Date : June 15, 2006<br/>
    * Time : 11:05 AM<br/>
    public class HTMLDocumentProcessor {
        // class fields
        private Properties tidyProperties   = null;
        private final String tidyConfigFile =
                "com/boeing/ict/pdemo/resources/TidyConfiguration.properties";
         * Creates a new instance of HTMLDocumentProcessor
        public HTMLDocumentProcessor() {
            initComponents();
        private void initComponents() {
            try {
                tidyProperties = new Properties();
                tidyProperties.load(ClassLoader.getSystemResourceAsStream(tidyConfigFile));
            } catch (IOException ignore) {
        public Document cleanPage(InputStream docStream) throws IOException {
            Document doc = null;
            NullOutputStream nos = new NullOutputStream(); // A NullOutputStream is
                                                           // is used to keep all the
                                                           // error output from printing
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // check to see if we were successful at loading properties
            if (tidyProperties.isEmpty()) {
                System.err.println("Unable to load configuration file for Tidy");
                System.err.println("Proceeding with default configuration");
            Tidy tidy = new Tidy();
            // set some local, non-destructive settings
            tidy.setQuiet(true);
            tidy.setErrout(new PrintWriter(nos));
            tidy.setConfigurationFromProps(tidyProperties);
            doc = tidy.parseDOM(docStream, bos);
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = null;
            try {
                docBuilder = docFactory.newDocumentBuilder();
            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            try {
                doc = docBuilder.parse(new ByteArrayInputStream(bos.toByteArray()));
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (SAXException ex) {
                ex.printStackTrace();
            // assuming everything has gone ok, we return the root element
            return doc;
        public static void main(String[] args) {
            try {
                String fileName = "C:/tmp/metars-search.htm";
                File htmlFile = new File(fileName);
                if (!htmlFile.exists()) {
                    System.err.println("File : " + fileName + " does not exist for reading");
                    System.exit(0);
                FileInputStream fis = new FileInputStream(htmlFile);
                HTMLDocumentProcessor processor = new HTMLDocumentProcessor();
                Document doc = processor.cleanPage(fis);
                if (doc == null) {
                   System.out.println("cleanPage(InputStream) returned null Document");
                   System.exit(0);
                NodeList spanTags = doc.getElementsByTagName("span");
                int numSpanTags = spanTags.getLength();
                for (int i = 0; i < numSpanTags; i++ ) {
                    System.out.println(spanTags.item(i).getTextContent().trim());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.exit(0);
    }

    Thank you Dr but the following is true:
    I placed this code in the for loop before I posted the question :
    for (int i = 0; i < numSpanTags; i++) { // Loop falls through here!
          System.out.println("Span tag (" + i + ") = " + spanTags.item(i));
    }And I receive 29 (The correct number) of non-null references to objects (Node objects) in the NodeList.
    When I replace the exact same for loop with this code :
    for (int i = 0; i < numSpanTags; i++) { // Loop falls through here!
          System.out.println("Span tag (" + i + ") = " + spanTags.item(i).getTextContent());
    }Nothing prints. This discussion has never been about "clever means to suppress exceptions" it has been precisely about why a loop that has the
    exact same references, exact same indices prints one time and doesn't print the other and does not throw an exception. If you can answer
    that question then I am interested. I am not interested in pursuing avenues that are incorrect, not understood and most importantly shot from the hip without much thought.

  • Not getting required output from XML transform in servlet

    I have an XML document and an XSL stylesheet that will produce the output I require when I use the Xalan in-line parser. However, I cannot manage to do the same in a servlet. I have trawled through loads of examples but can't find anything that works. It appears that the servlet is choking when I try to use:
    Document document = builder.parse(datafile);
    and the output in the browser is:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML><HEAD>
    <META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD>
    <BODY></BODY></HTML>
    Which bears no resemblance to what I am expecting.
    I can provide contents of servlet source and xml files if someone can help, please.

    Thanks for your comments.
    I have tested the XML and XSL and they are OK but the servlet won't sned out the HTML as expected.
    The servlet code is as follows (I haven't included the whole servlet - just the core of the body):
    public class FormTwo extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res)
         throws ServletException, IOException, FileNotFoundException {
    res.setContentType("text/html");
    //PrintWriter out = res.getWriter();
    PrintStream out = new PrintStream (res.getOutputStream());
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    TransformerFactory tFactory = TransformerFactory.newInstance();
    try {
      File stylesheet = new File("children.xsl");
      File datafile   = new File("children.xml");
      int NumChildren = Integer.parseInt(req.getParameter("Numchildren"));
      String fullname = req.getParameter("Title") + " " + req.getParameter("Lastname");
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.parse(datafile);
      // Use a Transformer for output
      StreamSource stylesource = new StreamSource(stylesheet);
      Transformer transformer = tFactory.newTransformer(stylesource);
      DOMSource source = new DOMSource(document);
      StreamResult result = new StreamResult(out);
      transformer.transform(source, result);
    }The XML is:
    <?xml version="1.0"?>
    <pagedef pagehead="Form two test page">
         <bodydef bodytext=", could you please enter details of each child and indicate if they are currently at school">
              <rows NumReq="3">
                   <cols type="text" size="25" name="firstname">First Name</cols>
                   <cols type="text" size="25" name="lastname">Last Name</cols>
                   <cols type="checkbox" name="atschool">At school?</cols>
              </rows>
         </bodydef>
    </pagedef>The XSLT is:
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
              xmlns="http://www.apache.org/xslt">
    <xsl:output method="html" indent="yes"/>
    <xsl:template match="/">
      <html>
      <head><title><xsl:value-of select="/pagedef/@pagehead"/></title></head>
      <body bgcolor="#ffffcc" text="#0000ff">
      <xsl:apply-templates/>
      </body>
      </html>
    </xsl:template>
    <xsl:template match="bodydef">
      <xsl:value-of select="@bodytext"/>
      <form>
      <table>
      <xsl:apply-templates/>
      </table>
      </form>
    </xsl:template>
    <xsl:template match="rows">
      <thead>
      <xsl:for-each select="cols">
      <td><xsl:value-of select="."/></td>
      </xsl:for-each>
      </thead>
      <xsl:call-template name="output-row">
      <xsl:with-param name="thisrow" select="0"/>
    </xsl:call-template>
    </xsl:template>
    <xsl:template name="output-row">
      <xsl:param name="thisrow"/>
      <xsl:choose>
      <xsl:when test="number($thisrow) != number(/pagedef/bodydef/rows/@NumReq)">
      <tr>
      <xsl:for-each select="cols">
      <td>
      <input>
      <xsl:copy-of select="@*"/>
      </input>
      </td>
      </xsl:for-each>
      </tr>
      <xsl:call-template name="output-row">
      <xsl:with-param name="thisrow" select="number($thisrow) + 1"/>
      </xsl:call-template>
      </xsl:when>
      <xsl:otherwise/>
      </xsl:choose>
    </xsl:template>
    </xsl:stylesheet>As a newbie to Java I am more confident about the XML and XSL than the servlet code. Any advice would be appreciated.
    Thanks...

  • Clarification for the parser to be used in wls6.1

    Hi,
    Let me confirm whether my underdstanding is correct becuase it was misleading
    on reading the FAQ of xml.Weblogic6.1 has two parsers xerces1.3.1 and weblogic
    fast parser and one cannot use any other version of xerces and xalan and can use
    any other parser by configuring in the xml registry and entering the DocumentBuilderFactory,SAXParserfactory
    and TransformerFactory .Is this right? please endorse it.
    sri

    I have found that all the Oracle SQL functions do work inside the SDO_RDF_MATCH procedure. I have used some of them as part of the filter parameter of the said procedure.
    Thanks
    Bhaskar

  • Enumeration mapping in message mapping

    I have a source structure ABC that contains two fields.  This structure needs to be transformed into two records that will store the field name of the source as well as the value.  It actually creates name/value pair in the target interface.  I wonder if message mapping could possibly handle that. 
    [Source]
    ABC
    ---FIELD_A = 123
    ---FIELD_B = 456
    [Target]
    DEF[0]
    ---NAME = "FIELD_A"
    ---VALUE = "123"
    DEF[1]
    ---NAME = "FIELD_B"
    ---VALUE = "456"
    Regards
    Chong Wah

    Hi Chong Wah,
    You can use the following java code to solve your problem using java mapping.
    * Created on Sep 14, 2005
    * To change the template for this generated file go to
    * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import com.sap.aii.mapping.api.StreamTransformation;
    * @author AnanthBabu Chinnaraj
    * To change the template for this generated type comment go to
    * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
    public class JavaMapping implements StreamTransformation {
         private Map map;
         private Document document;
         DOMSource domS = null;
         Document docOut = null;
         HashMap[] xmlData = null;
          * method setParamters is required, but we do not anything with it
         public void setParameter(Map param) {
              map = param;
          * method execute is called by the XI mapping program
         public void execute(InputStream in, OutputStream out) {
              HashMap[] xmlData = null;
              xmlData = parseInputXML(in);
              createOutputXML(xmlData[0], out);
         public static void main(String args[]) throws Exception {
              try {
                   JavaMapping mapObj = new JavaMapping();
                   FileInputStream in = new FileInputStream("D:/zAnanth/SDN/Src.xml");
                   FileOutputStream out =
                        new FileOutputStream("D:/zAnanth/SDN/Trgt.xml");
                   mapObj.execute(in, out);
              } catch (Exception e) {
                   e.printStackTrace();
          * method to process input xml
          * return array of HashMap for every 'ABC' tag
         public HashMap[] parseInputXML(InputStream in) {
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              try {
                   String tagName = null;
                   String tagValue = null;
                   // create DOM structure from input XML
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   document = builder.parse(in);
                   // look for the tag 'ABC'
                   NodeList list = document.getElementsByTagName("ABC");
                   //Initialize array size
                   xmlData = new HashMap[list.getLength()];
                   for (int i = 0; i < list.getLength(); i++) {
                        Node node = list.item(i);
                        //Initialize hashmap
                        xmlData<i> = new HashMap();
                        //Process Child nodes
                        NodeList childList = node.getChildNodes();
                        for (int j = 0; j < childList.getLength(); j++) {
                             Node childNode = childList.item(j);
                             if (childNode != null) {
                                  if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                                       //Store tag name
                                       tagName = childNode.getNodeName();
                                       //System.out.println("Name  *:"+childNode.getNodeName());
                                       //Store tag value
                                       tagValue = processValueNode(childNode);
                                       //Store as name value pair
                                       xmlData<i>.put(tagName.toUpperCase(), tagValue);
              } catch (Exception e) {
                   e.printStackTrace();
              return xmlData;
         private String processValueNode(Node childNode) {
              String tagValue = null;
              NodeList valueNodesList = childNode.getChildNodes();
              Node valueNode = valueNodesList.item(0);
              if (valueNode != null) {
                   if (valueNode.getNodeType() == Node.TEXT_NODE) {
                        tagValue = valueNode.getNodeValue();
                        //System.out.println("Value #:"+valueNode.getNodeValue());
              return tagValue;
          * Method to create xml document from input hashmaps
          * return XML doc in InputStream
         public void createOutputXML(HashMap xmlData, OutputStream out) {
              try {
                   DocumentBuilderFactory factory =
                        DocumentBuilderFactory.newInstance();
                   TransformerFactory tf = TransformerFactory.newInstance();
                   Transformer transform = tf.newTransformer();
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   //Create the output DOM
                   docOut = builder.newDocument();
                   //Create Top most Element
                   Element topRoot = docOut.createElementNS("http://XYZ", "ns:MT_ABC");
                   docOut.appendChild(topRoot);
                   Element defNode = null;
                   Set set = xmlData.keySet();
                   String[] tagNames = new String[set.size()];
                   set.toArray(tagNames);
                   for (int i = 0; i < tagNames.length; i++) {
                        defNode = createElement("DEF", topRoot);
                        createElement("Name", defNode, tagNames<i>);
                        createElement(
                             "Value",
                             defNode,
                             (String) xmlData.get(tagNames<i>));
                   //Process XML
                   domS = new DOMSource(docOut);
                   transform.transform((domS), new StreamResult(out));
              } catch (Exception e) {
                   e.printStackTrace();
         //Create an Element and add it into Parent
         private Element createElement(String elementName, Element parent) {
              Element ele = docOut.createElement(elementName);
              parent.appendChild(ele);
              return ele;
         //Create an Element and Text node and add it into Parent
         private Element createElement(
              String elementName,
              Element parent,
              String value) {
              Element ele = docOut.createElement(elementName);
              ele.appendChild(docOut.createTextNode(value));
              parent.appendChild(ele);
              return ele;
         //Get Values from Map, if value is null pass empty string
         private String getValue(HashMap map, String tagName) {
              String value = "";
              try {
                   value = (String) map.get(tagName);
                   if (value == null) {
                        value = "";
              } catch (Exception e) {
                   e.printStackTrace();
              return value;
    Regards,
    Ananth

  • Adding properties to XML Registry

    I'm using WLS 6.0. I was wondering if it is possible
    to add more properties into the XML Registry on the console.
    The two properties currently there are: DocumentBuilderFactory
    and SaxParserFactory.
    I'd like to add the two system properties: javax.xml.transform.TransformerFactory
    and org.xml.sax.driver.
    I know I can set these from the command line using the
    -D option but I'd much rather have the configuration
    in the console.
    Can I do this? If so, how?
    Thanks!

    Follow-up: Even though it lists 4 missing required properties in the error, when I went back and added only the Value property, the red flags went away....
    Werry Interestink!

  • Escape XML problem

    Hi,
    This is a FAQ, however, I did a search before posting to the forum but could not find a definite solution. Here is what I am trying to do:
    A webservice is returning a response XML and I am trying to display it on client console. I am able to display it properly on server side. The response is received by client of type 'Document'.
    I create a transformer to get a string and display it on the console, and this is how it is done:
    TransformerFactory tFactory =
        TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();
      DOMSource source = new DOMSource(document);
      StreamResult result = new StreamResult(System.out);
      transformer.transform(source, result);I get the writer out of the result and do 'toString()' to get the text. but the output shows & lt; instead of <  and similarly of > alsoWhat am I missing? and how do I fix this? Can anyone help me with this? Many of the posts direct to using the parser, i hope they refer to using DocumentBuilderFactory and then factory.parse(..) to get the document... but as I already have the document I did not use it...
    Thanx in advance.

    What you are missing is the explanation of why that is a problem.
    It's normal to escape "<" as "&lt;" if you are talking about data in a text node. But it is not normal to escape the "<" that starts a tag... unless you have an XML document embedded as a text node in an envelope-type document, in which case its tags are treated as text. This sort of thing happens in web services.
    So, do you have a problem? I'm not convinced you do.

  • ParserConfigurationException:

    Hi
    I am using MessageDrivenBean and WebsphereMq as JMS provider.I wil get the messages as string which are in xml format.using TransformerFactory and Transformer i wil convert the string as Xml,after that i wil parse the nodes of these xml and insert the details in database.For parsing i am using documentbuilder object.
    After processing few messages it is throwing ParserConfigurationException and it is happening rarely.Can anyone suggest me what will be the reason and how can i wil overcome this exception.
    The below is the code snippet throwing the exception.
           DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
              TransformerFactory transformerFactory = TransformerFactorynewInstance();
                                                   Transformer transformer = transformerFactory.newTransformer();
                   StringReader stingReader = new StringReader(message);
                   StreamSource src = new StreamSource(stingReader);
                   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                   StreamResult result = new StreamResult(outputStream);
                   transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                   transformer.transform(src, result);
                   ByteArrayInputStream inputStream = new ByteArrayInputStream(
                             outputStream.toByteArray());
                   InputSource inputSource = new InputSource(inputStream);
                   DocumentBuilder builder = builderFactory.newDocumentBuilder(); ----exception is throwing from here
                   Document document = builder.parse(inputSource);

    I am not having the stack trace.

  • Problem with com.sun.xml.parser.Parser

    Hi ,
    I am using weblogic 6.01.
    In my ejb class, I am parsing a String to create XmlDocument.
    I created xml registry in weblogic server.
    In my weblogic server's xml registry,
    I have com.sun.xml.parser.DocumentBuilderFactoryImpl as
    DocumentBuilderFactory
    and com.sun.xml.parser.Parser as parser.
    I am using jaxp 1.1 for all my xml related processing. All required jars are
    in the classpath.
    following is my code
    protected Document createDocument ( String a_sXmlDocument )
    try
    ByteArrayInputStream baInputStream = new ByteArrayInputStream
    (a_sXmlDocument.getBytes ());
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
    DocumentBuilder builder = factory.newDocumentBuilder ();
    Document xmlDocument = builder.parse (baInputStream);
    return xmlDocument ;
    catch (
    I get following exception at builder.parse ( baInputStream )
    Can't find bundle for base name com.sun.xml.parser.resources.Messages,
    locale en
    at com.sun.xml.parser.Parser.parseInternal(Parser.java:516)
    at com.sun.xml.parser.Parser.parse(Parser.java:284)
    at
    com.sun.xml.parser.DocumentBuilderImpl.parse(DocumentBuilderImpl.java
    :95)
    at
    weblogic.xml.jaxp.RegistryDocumentBuilder.parse(RegistryDocumentBuild
    er.java:98)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:78)
    at
    com.datamap.arch.datamap.BasicTransportableDelegate.createDocument(Ba
    I would appreciate if anyone could help in this exception.
    Thank you,
    Mahendra

    Hi ,
    I am using weblogic 6.01.
    In my ejb class, I am parsing a String to create XmlDocument.
    I created xml registry in weblogic server.
    In my weblogic server's xml registry,
    I have com.sun.xml.parser.DocumentBuilderFactoryImpl as
    DocumentBuilderFactory
    and com.sun.xml.parser.Parser as parser.
    I am using jaxp 1.1 for all my xml related processing. All required jars are
    in the classpath.
    following is my code
    protected Document createDocument ( String a_sXmlDocument )
    try
    ByteArrayInputStream baInputStream = new ByteArrayInputStream
    (a_sXmlDocument.getBytes ());
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
    DocumentBuilder builder = factory.newDocumentBuilder ();
    Document xmlDocument = builder.parse (baInputStream);
    return xmlDocument ;
    catch (
    I get following exception at builder.parse ( baInputStream )
    Can't find bundle for base name com.sun.xml.parser.resources.Messages,
    locale en
    at com.sun.xml.parser.Parser.parseInternal(Parser.java:516)
    at com.sun.xml.parser.Parser.parse(Parser.java:284)
    at
    com.sun.xml.parser.DocumentBuilderImpl.parse(DocumentBuilderImpl.java
    :95)
    at
    weblogic.xml.jaxp.RegistryDocumentBuilder.parse(RegistryDocumentBuild
    er.java:98)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:78)
    at
    com.datamap.arch.datamap.BasicTransportableDelegate.createDocument(Ba
    I would appreciate if anyone could help in this exception.
    Thank you,
    Mahendra

  • Attribute order changed

    Hello all!
    I'm developing a webapplication with JSP technology.
    i have to manage xml files, change and rewrite them.
    i use those pakage for manage and edit xml files :
    "javax.xml.parsers.DocumentBuilder and DocumentBuilderFactory"
    and that one for rewrite in a file:
    "javax.xml.transform"
    Now the problem is that the xml file edited had a particular element attribute order. the file rewrited change this order into an alphabetical order.
    i want to mantein the previous order.
    Is that possible? how?
    Thanks!

    No you get over it. The spec doesn't say it, but it is clearly an oversight by engineers more concerned with computer consuming XML then humans. One of the big selling points is that it is human readable and editable, this goes right against that.
    Now that XML is more of a standard, programming languages and other things are being generated using it. Configuration files and all sorts of things. Consider you have a tag like <function name="" comment="" >
    Suppose comment becomes really long while name is very short. Right now XSLT will reverse these attributes..now comment comes before the name and the file becomes unreadable....XML is used by humans too!
    The spec also doesn't say you need it or not. Java and the rest of the community have actively decided to be like you, a complete dick, for no reason and not support it. Just lazying coding for no reason. I guess maybe open standards are a bad way to go huh? Man up and have the right attitude...no reason not to make it an option other then total disregard for other peoples real world ( not virtual specification ) problems.

  • URGENT start tag needs to be generated in xml output

    I am getting the xml output as below
    since my value for each element is empty doesn't generate the start tag. BUT I NEED START TAG also to be created with this xml file. What property need to specify while generating it thro' Transformer and TransformerFactory. Please help me
    <?xml version="1.0" encoding="UTF-8"?>
    <address>
    <addressID/>
    <streetNumber/>
    <addressLine1/>
    <addressLine2/>
    <addressLine3/>
    <city/>
    <zipCode/>
    <lastUpdatedUserID/>
    <deletedFlag/>
    <phoneNumber/>
    <country/>
    <state/>
    </address>

    I don't quite understand your question. You want to have the start tag of each element outputed or you want one root element start tag to be outputed?
    If it's the first case, try separating start and end tags from your elements instead of having them combined, i.e. do the following:
    replace
    <addressLine1/>by
    ]<addressLine1>
    </addressLine1>I don't know if this is the answer you expect, reply if not.

  • Xml parsing exception

    Hi,
    I am having xml content as a string like below
    <?xml version="1.0" encoding="UTF-8"?>
    <TransactionResponse>
    <InterchangeControlHeader>
    <AuthorInfoQualifier>00</AuthorInfoQualifier>
    <AuthorInformation> </AuthorInformation>
    </InterchangeControlHeader>
    </TransactionResponse>
    I am trying to parse this xml using below code
    factory.setValidating(false);
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    StringReader XMLStringReader = new StringReader(xmlString);
    InputSource XMLInputSource = new InputSource(XMLStringReader);
    document = builder.parse(XMLInputSource);
    I am using
    javax.xml.parsers.DocumentBuilderFactory and DocumentBuilder for parsing but i am getting exception
    "The markup in the document preceding the root element must be well-formed"
    any idea what is missing?
    Thanks

    I am using websphere4.0.6,in standalone appln it works fine.

Maybe you are looking for

  • I AM READY TO SELL THIS MACBOOKPRO BUT I DO NOT GIVE-UP EASY...

    (I apologize for all the errors but I a too tired to correct them) I have so many problems but I will list a few to see if I can get some of these fixed 1. I was looking through a State f Utah Housing website that is put together by a couple guys. Th

  • Strange distorted colours on my ibook screen, blacks turn to reds, help!

    Hello! I am posting my display problem here so that i don't have to spend unnecessary money on it. So the problem began 3 days ago when i started my ibook, the apple logo that usually is the center of a blue screen, was a bit grey with some red highl

  • Using FILE to interact with the CI from an App server

    Hi All. We have a custom code function where a user takes a text file and uploads it into the SAP system. The file is immediately processed and a new 'outbound' file is created. Currently, we have the dirctory structure set-up on out CI/DB server. Ou

  • Quantity proposal in batch selection

    In batch search strategies you can select a quantity proposal routine to be used to allocagtge qtys to the proposed batches in a specific manner. I'm trying to locate where you add/change/modify these routines.  The help file indicates these are main

  • Bring Back "Apply Rotation"

    It appears we have the old 2 steps forward, 1 back scenario with image rotation. If you rotate an image in bridge it only rotates the preview. Yes if you open this image in Photoshop CS2 it will be rotated and will stay that way when you save it, but