Java 6: Transformer ignores OutputKeys.STANDALONE?

While testing a very old XML export job for being compatible with Java 6, I noticed a change in the output: the transformer now always adds a standalone="no" to the declaration, no matter what you've told it to do. Though this declaration is merely a hint to the parser, I find it somewhat annoying that even if standalone is set to "yes", the result will be "no" without being reflected in the docs. This happens under Java 6 only, whereas Java 1.4 and Java 5 honour the standalone property you set. Can anyone confirm/explain this?
Here's a test class which produces a very simple XML file named "out.xml" in the cwd:
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class XML
  public static void main(String[] args)
    try
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
      Transformer trans = TransformerFactory.newInstance().newTransformer();
      Element root = doc.createElement("root");
      Element elem = doc.createElement("elem");
      root.appendChild(elem);
      doc.appendChild(root);
      trans.setOutputProperty(OutputKeys.VERSION, "1.0");
      trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      trans.setOutputProperty(OutputKeys.STANDALONE, "yes"); // ignored? wtf
      trans.transform(new DOMSource(doc), new StreamResult(new File("out.xml")));
    catch (Exception ex)
      ex.printStackTrace();
}

Please try doc.setXmlStandalone(true);

Similar Messages

  • Java PI7.1 mapping and standalone NWDS debugging using local XML files

    >>which can be debugged in standalone NWDS using local files.
    yes its possible...u just have to add static void main (as sugested in the blog) ..
    Note: i dont have a system as of now..so i guess there can be some sysntax errors. Please check.
    create input xml file with name "input.xml" and place it under "D" drive (it can be any location)
    package prasad.NewAPI;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import com.sap.aii.mapping.api.AbstractTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import com.sap.aii.mapping.api.TransformationInput;
    import com.sap.aii.mapping.api.TransformationOutput;
    * @author Prasad Nemalikanti
    public class NewAPIJavaMapping extends AbstractTransformation {
    public static void main(String[] args) {
              try{
                   NewAPIJavaMapping javaMapping =new NewAPIJavaMapping();
                   FileInputStream in=new FileInputStream("D:\\input.xml");
                   FileOutputStream out=new FileOutputStream("D:\\output.xml");
                   javaMapping.execute(in,out);
                   catch(Exception e)
                   e.printStackTrace();
       String result="";
      /* The transform method which must be implemented */
      public void transform(TransformationInput in,TransformationOutput out) throws StreamTransformationException
        InputStream instream = in.getInputPayload().getInputStream();
      // String for constructing target message structure
        String fresult="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        fresult = fresult.concat("<ns0:MT_Customer xmlns:ns0=\"urn:newapi-javamapping\">");
        try{
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(instream);
            traversingXML(doc);
         catch(Exception e){}
    fresult = fresult.concat(result);
    fresult = fresult.concat("</ns0:MT_Customer>");
    try{
      out.getOutputPayload().getOutputStream().write(fresult.getBytes());
      /* assigning the created target message to "TransformationOutput"*/
       catch(IOException e1){}
    /*DOM Parser */
    public void traversingXML(Node node)
       NodeList children = node.getChildNodes();
       for(int i=0;i<children.getLength();i++)
         Node child = children.item(i);
         short childType = child.getNodeType();
         if(childType==Node.ELEMENT_NODE)
                  String nodeName=child.getNodeName();
                  String targetNodeName=null;
                  if(nodeName.equals("Users"))
                   targetNodeName="Customers";
                  else if(nodeName.equals("ID"))
                   targetNodeName="CustomerID";
                  else if(nodeName.equals("UserName"))
                   targetNodeName="Name";
                  else if(nodeName.equals("City"))
                    targetNodeName="City";
                  else if(nodeName.equals("State"))
                    targetNodeName="State";
                  else if(nodeName.equals("Country"))
                    targetNodeName="Country";
                 if(targetNodeName!=null)
                  result=result.concat("<"+targetNodeName+">");
       traversingXML(child);
       if(targetNodeName!=null)
       result=result.concat("</"+targetNodeName+">");
         else if(childType==Node.TEXT_NODE)
           String nodeValue = child.getNodeValue();
           result = result.concat(nodeValue);

    I have tested this and it is working..please chk the same
    package com.test;
    import java.io.IOException;
    import java.io.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import com.sap.aii.mapping.api.AbstractTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import com.sap.aii.mapping.api.TransformationInput;
    import com.sap.aii.mapping.api.TransformationOutput;
    public class JavaMapping extends AbstractTransformation {
           /* The transform method which must be implemented */
           public void transform(TransformationInput in,TransformationOutput out) throws StreamTransformationException
                this.execute(in.getInputPayload().getInputStream(),
                          out.getOutputPayload().getOutputStream());
           String result="";
           public void execute(InputStream in1, OutputStream out1)
          throws StreamTransformationException {
           // String for constructing target message structure
             String fresult="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
             fresult = fresult.concat("<ns0:MT_Customer xmlns:ns0=\"urn:newapi-javamapping\">");
             try{
                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                 DocumentBuilder builder = factory.newDocumentBuilder();
                 Document doc = builder.parse(in1);
                 traversingXML(doc);
              catch(Exception e){}
          fresult = fresult.concat(result);
          fresult = fresult.concat("</ns0:MT_Customer>");
          try{
           out1.write(fresult.getBytes());
           /* assigning the created target message to "TransformationOutput"*/
            catch(IOException e1){}
          /*DOM Parser */
          public void traversingXML(Node node)
            NodeList children = node.getChildNodes();
            for(int i=0;i<children.getLength();i++)
              Node child = children.item(i);
              short childType = child.getNodeType();
              if(childType==Node.ELEMENT_NODE)
                       String nodeName=child.getNodeName();
                       String targetNodeName=null;
                       if(nodeName.equals("Users"))
                        targetNodeName="Customers";
                       else if(nodeName.equals("ID"))
                        targetNodeName="CustomerID";
                       else if(nodeName.equals("UserName"))
                        targetNodeName="Name";
                       else if(nodeName.equals("City"))
                         targetNodeName="City";
                       else if(nodeName.equals("State"))
                         targetNodeName="State";
                       else if(nodeName.equals("Country"))
                         targetNodeName="Country";
                       if(targetNodeName!=null)
                           result=result.concat("<"+targetNodeName+">");
            traversingXML(child);
            if(targetNodeName!=null)
                 result=result.concat("</"+targetNodeName+">");
              else if(childType==Node.TEXT_NODE)
                String nodeValue = child.getNodeValue();
                result = result.concat(nodeValue);
          public static void main(String[] args) {
                   try{
                        JavaMapping javaMapping =new JavaMapping();
                        FileInputStream in=new FileInputStream("D:\\Input.xml");
                        FileOutputStream out=new FileOutputStream("D:\\output.xml");
                        javaMapping.execute(in,out);
                        catch(Exception e)
                        e.printStackTrace();
    AM

  • OIM Java API silently ignores accounts operations such as enable/disable/revoke

    Hi
    I am facing a strange situation here.
    My Java app (standalone) was able to set provisioned accounts to "enabled" and then disabled these enabled ones.
    Now, provisioned accounts can't be enabled anymore.
    Commands issued from Java API using ProvisioningService such as "enable", "disable" and "revoke" are being simply ignored. No exception raised, no changes.
    Am I missing some step? Do I need to run any scheduled job in order to "commit" these changes performed from the OIM Java API?
    How do I debug this?
    TIA

    Sorry for my ignorance, but where's this "resource history" thing in OIM?
    Here's what I am doing.
    First, I use the Self Service UI to provision an account. This account belongs to an application instance backed by the OIM Webservice connector.
    I suppose it works because after requesting the account, the connector creates it and returns back a unique ID (which is assigned to the account uid) and the account shows up in "my accounts" tab as "provisioned".
    So far, so good.
    THEN
    I run my standalone java app from outside OIM, which uses OIM Java API. This app connects to OIM as xelsysadm, and I search for the account and do something like this
    public void enableAccount(String uid) throws AccessDeniedException, NumberFormatException, AccountNotFoundException, ImproperAccountStateException,
        GenericProvisioningException, InvalidUidException {
      Account a = findAccountIdByUID(uid);
      if (a != null) {
        System.out.println("enabling "+a.getAccountID()+":"+a.getAccountStatus()+":"+a.getAccountData().getData().get("UD_AVNC_USR_LOGIN")); <<< here I confirm I am changing the right account, it is
        ProvisioningService provService = oimClient.getService(oracle.iam.provisioning.api.ProvisioningService.class);
        provService.enable(Long.parseLong(a.getAccountID()));
      }else {
        throw new InvalidUidException(uid);
    then I expect to refresh "my accounts" tab and see my account status changed from "Provisioned" to "Enabled".
    I don't know if these screenshots may help, but anyway
    These are the tasks for the provisioning process. I believe the one we're interested here is the #22
    these are the status definitions for the process. They're also created by default during the OIM webservice connector module import process I guess
    these are the task to object status mapping for the task #22 below, also created automatically I guess.
    I am a little bit confused because the OIM manual -- http://docs.oracle.com/cd/E27559_01/user.1112/e27151/myaccess.htm#OMUSG3166 -- says the user can just perform the operations on the accounts, but says nothing about any kind of restriction. I mean, what are exactly the state transition for accounts (the default one)?
    TIA

  • Jsp/jstl/java bean to connect to standalone app in another language

    hello.
    i want to integrate all the existing applications that we have into one single online application. problem is, some of the existing applications are standalong done in different languages like java(in j2se), visual basic and c.
    i want to make a menu with a link and in clicking taht link , i want it to execute that standalone application. is that possible?
    any help would be much much appreciated
    thanks

    window.open(URL,'logWin01',winProps);
    use the above function to launch new browser window.... it takes three arguments,
    1) the URL of the window i.e., the jsp/html page which should be shown in the new window.
    2) title of the window
    3) properties of the window with coma "," seperated example
    window.open("/CarrierMaskHelpPopup.jsp", "PopUpWindow1", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no");

  • How do you deal with this Exception in Java xml transformation

    I was trying to use a java class to do a multiple transformation on and xml file that consists of several xml codes as files.
    This is the Error i got
    Exception in thread "main" java.lang.OutOfMemoryError

    Increase the memory maximum java is allowed to consume, e.g.
    java -Xmx512m ...for a maximum of 512 Megs.
    Regards

  • Does Java Plug-in Ignore java.policy Permissions?

    I am running Firefox 3.6.12 on Ubuntu Karmic with Java plug-in 1.6.0_22. I'm trying to run an Aventail OnDemand applet, and I keep getting I/O file-reading permissions exceptions in the Java console. I tried granting the permission in /usr/lib/jvm/java-6-sun-1.6.0.22/jre/lib/security/java.policy, but that was apparently ignored. Any help would be greatly appreciated.

    I think the java plugin uses C:\Program Files\Java\j2re1.4.2_04\lib\security\cacerts as a store to get keys.
    The password of this file is changeit and you can use keytool to import keys.
    I found contradicting information about what can be imported but if you have a p12 file (Mozilla convention for PKCS12) you can import it with java control panel:
    C:\Program Files\Java\j2re1.4.2_04\bin\jpicpl32.exe
    After imported a cert with control panel it was put in a file located here
    C:\Documents and Settings\sbaker\Application Data\Sun\Java\Deployment\security\
    Importing with the control panel makes a user specific import and importing with keytool in C:\Program Files\Java\j2re1.4.2_04\lib\security\cacerts (password is changeit) makes it machine specific.

  • Java.lang.OutOfMemoryError while starting Standalone Reports Server

    I am trying to start a standalone report server on AIX box, but is giving following error
    bash-3.00$ rwserver.sh server=repservername &
    java.lang.OutOfMemoryError: JVMXE006:OutOfMemoryError, stAllocAor executeJava failed
    kindly help

    was able to solve this
    there was corruption of reports config file

  • Java developer visual toolkit in standalone

    Hi:
    I am looking for a visual toolkit for development under java, no web needed, just the ability to create screens, database access and graphs with java, in standalone.
    Do you have the name of that kind of toolkit?
    Thanks in advance.
    Pilar Angeles

    Hi java_angeles,
    Thanks for the interest shown for products at Sun Microsystems.
    Sun Java Studio Creator provides the drag-and-drop, RAD approach to J2EE development .Java Studio Creator puts together a number of new technologies such as Java Server Faces (JSF) , JDBC Rowsets and Web Services APIs to give J2EE developers a relaxed feeling when building web applications. The current version of the IDE includes features for Rapid application development with EJB consumption. An easy deployment and testing facility.
    Please do have a walk through on the following link to get some vital information about the product.
    http://developers.sun.com/prodtech/javatools/jscreator/index.jsp
    http://www.sun.com/software/products/jscreator/features.xml
    Cheers :)
    Creator Team.

  • Java.lang.UnsatisfiedLinkError in JDeveloper standalone CMSDK application

    When I try to run my standalone Content Management application on my development PC against a Content Management SDK deployed on another server (using jvm runtime parameters as in CM WebStarterApp II -DIFS.DOMAIN.Name=ifs://xtorc1:1521:test:CMSDK -DIFS.STANDALONE.Mode=true -DIFS.SCHEMA.PASSWORD=welcome), I got " IFS-20103: Unable to get sessions". When I debug the code, I notice the actual error as following:(I've tested it using JDeveloper versions 10.1.2 and 9.0.4)
    (in JDeveloper 10.1.2):
    java.lang.UnsatisfiedLinkError: int oracle.jdbc.driver.T2CConnection.t2cCreateState(byte[], int, byte[], int, byte[], int, short, int, short[], byte[], byte[])
    (in JDeveloper 9.0.4):
    java.lang.UnsatisfiedLinkError: int oracle.jdbc.oci8.OCIDBAccess.make_c_state(boolean)
    I've checked the metalink and the forums, however nothing helped me solve the problem so far. It seems like the JDeveloper is confusing the oci driver (the dll's) somehow, however I checked my PATH in my environment, everything seems OK.
    I was trying to run a standalone IFS (CM SDK) web application in development machine,
    in JDeveloper's embedded OC4J server, against the CM SDK domain on another
    server where the Application Server resides. The logon page appears and after
    submitting the form the following piece of code returns the error:
    String schemaPassword = System.getProperty("IFS.SCHEMA.PASSWORD");
    String domainName = System.getProperty("IFS.DOMAIN.Name");
    try
    //the exception is caused by the following line
    m_LibraryService = LibraryService.startService(serviceName, schemaPassword,
    null, domainName);
    catch (Throwable e)
    // the exception is caught here
    Any ideas??
    Özgür

    I see that you're doing your conection using oci8; I had the same problem and my solution was changed to thin
    For example: jdbc:oracle:thin:@IP_ADDRESS:PORT:SID
    I hope it can help to you

  • Simple Transformation - ignore processing a block

    Hi!
    Here is a portion of an XML document that I want to parse into an ABAP structure:
        <field1 attrib1="xyz" attrib2="pqr"/>
        <field2 attribA="xyz" attribB="pqr"/>
        <content type="application/xml">
          <field label="Customer Number" name="customer_id_disp">0000000011</field>
          <field label="Customer Title Code" name="title_code"></field>
          <field label="Person's Title" name="title"></field>
          <field label="First Name" name="first_line_name">Heavy Tool Plt</field>
          <field label="Second/Last Name" name="second_line_name"></field>
          <field label="Third Name/Mid Name" name="third_line_name"></field>
          <field label="Fourth Name/ Given Name" name="fourth_line_name"></field>
          <field label="Revenue Amount" name="revenue_amount">0.0</field>
        </content>
    Now my structure looks something like this:
    xmlstructure (structure)
          |_ field1 (structure)
          |       |_ attrib1 (string)
          |       |_ attrib2 (string)
          |
          |_ field2 (structure)
          |       |_ attribA (string)
          |       |_ attribB (string)
          |
          |_ content (structure)
                  |_ type (string)
                  |_ text (string)
    Basically, I want to process the 'content' later on (not in the first pass), and simply store it into the structure field xmlstructure-content-text for now. I assume the simple transformation code for doing this would be:
              <content>
                <tt:attribute name="type" value-ref="CONTENT.TYPE"/>
                <tt:value ref="CONTENT.TEXT"/>
              </content>
    But the moment the ST encounters the line <tt:value ref="CONTENT.TEXT"/>, it throws a runtime error. (because it is expecting handling for the <field> element.
    How do I get around this problem?

    You need to add conditional check for the node attribute.
    Exp:
    <tt:d-cond check="exist(ABCD)">
    <ABCD tt:value-ref="ABCD"/>
    </tt:d-cond>

  • Java.policy codebase ignored

    I've recently been trying to allow an applet on a local webpage to write to a file in the same folder. I've been using the following .java.policy file:
    grant codeBase "file:${user.home}/My Documents/folder/*" {
      permission java.io.FilePermission "${user.home}${/}My Documents${/}folder${/}*", "read,write";
    };The HTML is in the folder called "folder" as above. So is the JAR file for the applet. In the HTML is:
    <applet code="foo.class" archive="foo.jar"></applet>The applet implements a "load" function and a "save" function, which are called like:
    data=document.applets[0].load(filename);
    document.applets[0].save(filename,data);Everything works perfectly using Opera, but fails in IE and Firefox unless I remove the codebase from the grant, leaving just a universal "grant {".
    I'm using 1.5.0_06. I've tried other codeBase values such as "file:C:/-", "file:///C:/-", "file:C:/Documents%20and%20Settings/-", and similar variations (too many to list). I've also tried adding a codebase attribute to the applet tag with the value "file:///C:/Documents%20and%20Settings/username/My%20Documents/folder/" (value derived from document.location).
    Is there some way to limit granting of permissions to applets in a particular folder that works in all browsers? I know Opera bypasses the Java plugin to access the runtime directly, hence my feeling this is a plugin bug.
    Thanks in advance for any help.

    Use doprivileged for signed code called by javascript
    Signing applets:
    http://forum.java.sun.com/thread.jsp?forum=63&thread=524815
    second post and last post for the java class file using doprivileged
    Still problems?
    A Full trace might help us out:
    http://forum.java.sun.com/thread.jspa?threadID=656028

  • Is it possible to Use Java Studio Creator to create standalone Apps

    I am looking for a good Java IDE for client application development. I used to use JBuilder, but it doesn't work on the Intel line of Macs.
    I have been checking out Jaca Studio Creator, but it seems to only be for server apps.
    Is there a download somewhere that will enable this?
    Thanks, Michael

    Have you looked at http://www.netbeans.org or http://developers.sun.com/prodtech/javatools/jsenterprise/index.jsp?

  • What JDK version to use for the Java/XML transformation?

    Hi,
    I am working on Generating an XML Document from XML Schema with JAXB .
    I am doing this for one of Oracle' s internal fusion products.
    I am using JDK 1.5.
    What version of JDL shall I use so that it doesn't conflict with future requirements.
    Thanks
    Sanjeev ([email protected])

    What version of JAXB?
    For JAXB 1.0 use JDK 1.4
    For JAXB 2.0 use JDK 5.0/6.0

  • Parsing XML using java DOM

    hi
    i am trying to parse a document and change a specific text value within an element althouh when i run the program it changes the nodes text however when i check the xml file it doesnt show the changes it remains the same the code that i am using is as follow iwould be greatful if any one culd help:
    //  ReplaceText.java
    // Reads intro.xml and replaces a text node.
    // Java core packages
    import java.io.*;
    // Java extension packages
    import javax.xml.parsers.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import javax.xml.transform.dom.*;
    // third-party libraries
    import org.xml.sax.*;
    import org.w3c.dom.*;
    public class ReplaceText {
       private Document document;
       public ReplaceText()
          // parse document, find/replace element, output result
          try {
             // obtain default parser
             DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
             // set parser as validating          
             factory.setValidating( true );
             // obtain object that builds Documents
             DocumentBuilder builder = factory.newDocumentBuilder();
             // set error handler for validation errors
             builder.setErrorHandler( new MyErrorHandler() );
      System.err.println( "reading" );
             // obtain document object from XML document
             File f = new File("D:/Documents and Settings/Administrator/Desktop/xml adv java bk/appC/intro.xml");
              System.err.println( "reading" );
             document = builder.parse(f);
    //document = builder.parse( new File( "intro.xml" ) );
    System.err.println( "reading document" );
             // retrieve the root node
             Node root = document.getDocumentElement();
             if ( root.getNodeType() == Node.ELEMENT_NODE ) {
                Element myMessageNode = ( Element ) root;
                NodeList messageNodes =
                   myMessageNode.getElementsByTagName( "message5" );
                if ( messageNodes.getLength() != 0 ) {
                   Node message = messageNodes.item( 0 );
                        System.out.println("iiiii");
                   // create text node
                   Text newText = document.createTextNode(
                      "New Changed Message!!" );
                   // get old text node
                   Text oldText =
                      ( Text ) message.getChildNodes().item( 0 ); 
                   // replace text
                   //message.removeChild(oldText);
                   message.replaceChild( newText, oldText );
             // output Document object
             // create DOMSource for source XML document
             Source xmlSource = new DOMSource( document );
             // create StreamResult for transformation result
             Result result = new StreamResult( System.out );
             // create TransformerFactory
             TransformerFactory transformerFactory =
                TransformerFactory.newInstance();
             // create Transformer for transformation
             Transformer transformer =
                transformerFactory.newTransformer();
             transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
               transformer.setOutputProperty( OutputKeys.STANDALONE, "yes" );
             // transform and deliver content to client
             transformer.transform( xmlSource, result );
          // handle exception creating DocumentBuilder
          catch ( ParserConfigurationException parserException ) {
             parserException.printStackTrace();
          // handle exception parsing Document
          catch ( SAXException saxException ) {
             saxException.printStackTrace();        
          // handle exception reading/writing data
          catch ( IOException ioException ) {
             ioException.printStackTrace();
             System.exit( 1 );
          // handle exception creating TransformerFactory
          catch (
             TransformerFactoryConfigurationError factoryError ) {
             System.err.println( "Error while creating " +
                "TransformerFactory" );
             factoryError.printStackTrace();
          // handle exception transforming document
          catch ( TransformerException transformerError ) {
             System.err.println( "Error transforming document" );
             transformerError.printStackTrace();
       public static void main( String args[] )
          ReplaceText replace = new ReplaceText();   
    }the xml file that i am using is as follows:
    <?xml version = "1.0"?>
    <!-- Fig. 28.10 : intro.xml             -->
    <!-- Simple introduction to XML markup   -->
    <!DOCTYPE myMessage [
         <!ELEMENT myMessage (message, message5)>
         <!ELEMENT message (#PCDATA)>
         <!ELEMENT message5 (#PCDATA)>
    ]>
    <myMessage>
         <message>welcome to the xml shhhhhushu</message>
         <message5>welcome to the xml shhhhhushu</message5>
    </myMessage>i would be greatful if some one could please help.....

    See if the Text 'oldText' actually has any text within it. Sometimes in DOM parsing, you will get something like:
    Element
       Text (blank)
       Text (actual)
       Text (blank)Whereas you would expect to receive:
    Element
       Text (actual)See if that is the case. If yes, modify your logic to iterate through the child text nodes until one with actual text inside of it (getNodeValue()) is found.
    - Saish

  • Help with Java to XML

    All I need to know is how to bold the tag <CompanyID> </CompanyID> OR the text within it (1001, in given sample).
    Here's a sample line of the data.txt file I'm working with:
    1001,"Fitzsimmons, Des Marteau, Beale and Nunn",109,"COD","Standard",,109,8/14/1998 8:50:02
    Thanks in advance!
    public class PracticeExerciseOne {
        public static void main(String [] args){
            DocumentBuilderFactory domFac = null;
            DocumentBuilder domBuild = null;
            //Element tags
            final String COMPANY = "Companies";
            final String COMPANY_ID = "CompanyID";
            //rest too long to post
            //Regex to be used for each field in the CSV file
            ArrayList<Pattern> patterns = new ArrayList<Pattern>();
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("[^,]*,"));
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("[^,]+ [^,]+"));
            //Store element tags in an array - too long to post
            try{
                //Build a new documet
                domFac = DocumentBuilderFactory.newInstance();
                domBuild = domFac.newDocumentBuilder();
                Document doc = domBuild.newDocument();
                //Create a new root element
                Element rootElement = doc.createElement(COMPANY);
                doc.appendChild(rootElement);
                //Read in the file
                BufferedReader in = new BufferedReader(new FileReader(new File("texts/data.txt")));
                BufferedWriter out = new BufferedWriter(new FileWriter(new File("texts/dataOut.xml")));
                int tempI;
                String line = in.readLine();
                //We will cut this string down after every element we take out of it
                String temp = line;
                String tempElement = "";
                while(line != null){
                    for(int i = 0; i < patterns.size(); i++){
                        //Matches a pattern to a field, starting with the first pattern
                        //Matchup should be 1st pattern = 1st field
                        Matcher matcher = patterns.get(i).matcher(temp);
                        if(matcher.find()){
                            //if we haven't reached the last field
                            if(i != 7){
                                //we want to get the index of the last comma within the matched group
                                tempI = matcher.group().lastIndexOf(',');
                                //create an element using the beginning of the given string and the last comma within that data
                                tempElement = temp.substring(0,tempI);
                            else{
                                //no comma in last field, so we just want to get the whole field
                                tempI = 0;
                                tempElement = temp.substring(0);
                            //if an empty element appears, add a space for tags to be placed correctly
                            if(tempElement.equals("")){
                                tempElement = " ";
                            //temp will be set to the remaining string, once we have taken the nth field out
                            temp = temp.substring(tempI+1);
                            //create an element with tags and append to document
                            Element em = doc.createElement(tags);
    em.appendChild(doc.createTextNode(tempElement));
    rootElement.appendChild(em);
    line = in.readLine();
    temp = line;
    //Transformer will create a new XML document using the Document we have built
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    transformer.transform(source, result);
    out.close();
    in.close();
    catch(Exception e){
    System.err.println("Exception: " + e.getMessage());
    e.printStackTrace();

    maybe this can help You for now and future,
    in this site You can download a sample codes publish in this books - java fundamentals and advanced features.,
    in 2nd book, is a big chapter about java and xml. Please read this code, i will hope, this can help You.
    http://www.horstmann.com/corejava.html (for mod: this is not SPAM)

Maybe you are looking for