Saturday, 13 June 2020

Salesforce DX and Most Popular Commands

What is Salesforce DX?

Salesforce Developement Experience (DX) is a set of tools that streamlines the entire development life cycle. It brings modern software delivery and development practices to the Salesforce platform. 

Salesforce DX offers you an open and standard developer experience, which helps you build application using the tools like Git, Eclipse, Selenium and more. Salesforce DX consists of an updated Eclipse Integrated Development environment (IDE) which expands the value of the toolset to salesforce developers.

A Salesforce DX project is a local directory structure of your metadata in source format. It lets you develop and test with Salesforce DX tooling. It improves team development and collaboration, facilitates automated testing and continuous integration, and makes the release cycle more efficient and agile.


Commands:


1) Login to New Org and Set the org as Default:

        sfdx force:auth:web:login -d -a DevHub

2) Create an new project:

        sfdx force:project:create -n ExampleProjectName

        

3) Create New scratch org:

        sfdx force:org:create -s -f config/project-scratch-def.json - a ScrachOrgNameExample

4) Pull code:

        sfdx force:source:pull

5) Push code:

        sfdx force:source:push
    

6) open scratch org:

        sfdx force:org:open

7) Generate password for scratch org user:

        sfdx force:user:password:generate --targetUserName

8) See the password for scratch org user:

        sfdx force:user:display -u
   

Monday, 8 June 2015

Integrate Force.com SOAP API with Java Apps Using Force.com Web Services Connector (WSC)

Services This blog post will describe you that how to integrate Salesforce - Force.com SOAP API with Java Apps.

Below is an example of how to integrate Force.com SOAP API with Java Apps using Eclipse IDE.

Introduction to the Force.com Web Services Connector

The Force.com Web Services Connector (WSC) is a code-generation tool and runtime library for use with Force.com Web services. WSC uses a high-performing Web services client stack implemented with a streaming parser. It is the preferred tool for working with salesforce.com APIs. You can write Java applications with WSC that utilize the Force.com SOAP API, Bulk API, and Metadata API. There are even runtime libraries that let you access the Force.com SOAP API from applications running on Google App Engine.

Using WSC, you can perform operations with a few lines of code that would take many more lines of code with other Web services clients.

This article provides an introduction to WSC. The WSC can be used to invoke any doc-literal wrapped Web service, but in this article we’ll focus on the SOAP API with both the enterprise and partner WSDLs, and the Metadata API. Along the way, you’ll learn how to get started with WSC, and see an example of a console application that demonstrates WSC functionality.

Introduction to Force.com
Force.com has several API's including:
  • Force.com SOAP (Simple Object Access Protocol) API
  • Force.com Metadata API
  • Force.com Bulk API
  • Force.com Streaming API
  • Force.com REST (Representational State Transfer) API
  • Force.com Chatter API
Preparing to Integrate Java Apps with Force.com APIs:
I am assuming you have some experience building Java applications with Force.com APIs.

To get started, we'll run through the following steps:

1) First you need to install "Java JDK (6 or 7)" in your machine.
2) Second you need to check whether "Java JDK (6 or 7)" has installed successfully or not?

Just type in the command prompt:
java -version

You will the result same as below:
It will show you:
java version "1.6.0_35"
Java(TM) SE Runtime Environment (build 1.6.0_35-b10-428-10M3811)
Java HotSpot(TM) 64-Bit Server VM (build 20.10-b01-428, mixed mode)

Note: If you get error then change your command prompt directory to the Java bin directory and test it again.

For Example:
C:\Program Files\Java\jdk1.6.0_45\bin> java -version

3) Download the "Enterprise WSDL" or "Partner WSDL" from your salesforce.com organization.

Log in into salesforce.com organization -> User Name ->  Setup -> App Setup section -> Develop -> API -> click on Generate Enterprise or Partner WSDL -> Save file with extension ".wsdl" as "enterprise.wsdl" or "partner.wsdl".

4) Download the Web Services Connector (WSC) "wsc-20.jar" file from the URL"http://code.google.com/p/sfdc-wsc/downloads/list".

5) Now create JAR (Java ARchive) files for "enterprise.wsdl" and "partner.wsdl" files.

6) Copy the "tools.jar" file from the path where you have installed "Java JDK (6 or 7)".

For Example:
"C:\Program Files\Java\jdk1.6.0_45\lib\tools.jar" and paste it in your "E:\" drive. I am doing this just for safe side so we don't have any conflicts.

Note: 
(a) "tools.jar" and "wsc-20.jar" file both must be in the same directory otherwise, you will get an error "classpath: java.io.FileNotFoundException".
(b) Just for safe side I would recommend that your "E:\" drive must have "tools.jar", "wsc-20.jar", "enterprise.wsdl" and "partner.wsdl".

6) Execute the following command to generate JAR File "JAR file (Java ARchive)" for "enterprise.wsdl" or "partner.wsdl".

For Example:
java -classpath wsc-XX.jar com.sforce.ws.tools.wsdlc enterprise.wsdl enterprise.jar

Real Example:
Generate enterprise.jar
java -classpath E:\tools.jar;E:\wsc-20.jar com.sforce.ws.tools.wsdlc E:\enterprise.wsdl E:\enterprise.jar

Generate partner.jar
java -classpath E:\tools.jar;E:\wsc-20.jar com.sforce.ws.tools.wsdlc E:\partner.wsdl E:\partner.jar

Now these commands will generate "enterprise.wsdl" or "partner.wsdl".

Generate Java Code in Eclipse (Creating an Enterprise WSDL Application)

Now that your environment is ready to go, it's time to build a test application to see how things are working. Most developers build client applications with the enterprise WSDL, so we’ll start with that one first.
In Eclipse, complete the following steps to build a Java application based on the enterprise WSDL.
  1. Create a new Java project named “WSC - Enterprise” (click File | New | Java Project).
  2. Add the wsc-XX.jar and enterprise.jar to the project (click Project | Properties | Java Build Path | Libraries or External Libraries, then add the JARs to the project.
  3. Add a new folder, wsc, to the src folder in your app (right-click src in Package Explorer, then click New | Folder).
  4. Create a new class src/wsc/Main.java and paste in the code from the code listing that follows.
  5. Replace the stub user credentials in the code with your own user name and password with security token for the appropriate static members, then save your source code.
  6. Run the application.
Your Project in Eclipse IDE will look like below screenshot:










/********************************************************************************/
package wsc;

import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.DeleteResult;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Contact;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class Main {

static final String USERNAME = "YOUR-USERNAME";
static final String PASSWORD = "YOUR-PASSWORD&SECURITY-TOKEN";
  static EnterpriseConnection connection;

  public static void main(String[] args) {

    ConnectorConfig config = new ConnectorConfig();
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);
    //config.setTraceMessage(true);

    try {
 
      connection = Connector.newConnection(config);
 
      // display some current settings
      System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
      System.out.println("Service EndPoint: "+config.getServiceEndpoint());
      System.out.println("Username: "+config.getUsername());
      System.out.println("SessionId: "+config.getSessionId());
 
      // run the different examples
      queryContacts();
      createAccounts();
      updateAccounts();
      deleteAccounts();
 
 
    } catch (ConnectionException e1) {
        e1.printStackTrace();
    }

  }

  // queries and displays the 5 newest contacts
  private static void queryContacts() {

    System.out.println("Querying for the 5 newest Contacts...");

    try {
   
      // query for the 5 newest contacts  
      QueryResult queryResults = connection.query("SELECT Id, FirstName, LastName, Account.Name " +
       "FROM Contact WHERE AccountId != NULL ORDER BY CreatedDate DESC LIMIT 5");
      if (queryResults.getSize() > 0) {
        for (int i=0;i<queryResults.getRecords().length;i++) {
          // cast the SObject to a strongly-typed Contact
          Contact c = (Contact)queryResults.getRecords()[i];
          System.out.println("Id: " + c.getId() + " - Name: "+c.getFirstName()+" "+
              c.getLastName()+" - Account: "+c.getAccount().getName());
        }
      }
 
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  // create 5 test Accounts
  private static void createAccounts() {

    System.out.println("Creating 5 new test Accounts...");
    Account[] records = new Account[5];

    try {
   
      // create 5 test accounts
      for (int i=0;i<5;i++) {
        Account a = new Account();
        a.setName("Test Account "+i);
        records[i] = a;
      }
 
      // create the records in Salesforce.com
      SaveResult[] saveResults = connection.create(records);
 
      // check the returned results for any errors
      for (int i=0; i< saveResults.length; i++) {
        if (saveResults[i].isSuccess()) {
          System.out.println(i+". Successfully created record - Id: " + saveResults[i].getId());
        } else {
          Error[] errors = saveResults[i].getErrors();
          for (int j=0; j< errors.length; j++) {
            System.out.println("ERROR creating record: " + errors[j].getMessage());
          }
        }
      }
 
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

 //updates the 5 newly created Accounts
  private static void updateAccounts() {
   
    System.out.println("Update the 5 new test Accounts...");
    Account[] records = new Account[5];
   
    try {
     
      QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " + "CreatedDate DESC LIMIT 5");
      if (queryResults.getSize() > 0) {
        for (int i=0;i<queryResults.getRecords().length;i++) {
          // cast the SObject to a strongly-typed Account
          Account a = (Account)queryResults.getRecords()[i];
          System.out.println("Updating Id: " + a.getId() + " - Name: "+a.getName());
          // modify the name of the Account
          a.setName(a.getName()+" -- UPDATED");
          records[i] = a;
        }
      }
     
      // update the records in Salesforce.com
      SaveResult[] saveResults = connection.update(records);
     
      // check the returned results for any errors
      for (int i=0; i< saveResults.length; i++) {
        if (saveResults[i].isSuccess()) {
          System.out.println(i+". Successfully updated record - Id: " + saveResults[i].getId());
        } else {
          Error[] errors = saveResults[i].getErrors();
          for (int j=0; j< errors.length; j++) {
            System.out.println("ERROR updating record: " + errors[j].getMessage());
          }
        }  
      }
     
    } catch (Exception e) {
      e.printStackTrace();
    }  
   
  }
 
  // delete the 5 newly created Account
  private static void deleteAccounts() {
   
    System.out.println("Deleting the 5 new test Accounts...");
    String[] ids = new String[5];
   
    try {
     
      QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " + "CreatedDate DESC LIMIT 5 OFFSET 5");
      if (queryResults.getSize() > 0) {
        for (int i=0;i<queryResults.getRecords().length;i++) {
          // cast the SObject to a strongly-typed Account
          Account a = (Account)queryResults.getRecords()[i];
          // add the Account Id to the array to be deleted
          ids[i] = a.getId();
          System.out.println("Deleting Id: " + a.getId() + " - Name: "+a.getName());
        }
      }
     
      // delete the records in Salesforce.com by passing an array of Ids
      DeleteResult[] deleteResults = connection.delete(ids);
     
      // check the results for any errors
      for (int i=0; i< deleteResults.length; i++) {
        if (deleteResults[i].isSuccess()) {
          System.out.println(i+". Successfully deleted record - Id: " + deleteResults[i].getId());
        } else {
          Error[] errors = deleteResults[i].getErrors();
          for (int j=0; j< errors.length; j++) {
            System.out.println("ERROR deleting record: " + errors[j].getMessage());
          }
        }  
      }
     
    } catch (Exception e) {
      e.printStackTrace();
    }  
   
  }

}
/********************************************************************************/
Helpful Links:

Friday, 29 May 2015

Encryption and Decryption In Salesforce

Encryption, is the process of changing information in such a way as to make it unreadable by anyone except those possessing special knowledge (usually referred to as a "key") that allows them to change the information back to its original, readable form.
To encrypt some value we have to use some key value that can be hard coded or we can generate key also by using this 

Blob cryptoKey = Crypto.generateAesKey(256);
We have to use same key to decrypt that value.

Here I am going to share some code.Hope it will help you. I have created one visualforce page and one controller. In the page only one field(Name) is there and two button(Save & Update).
When some value is entered in the name field and clicked on save button that value will be stored in the object encrypted format.
Now record id in the url and click on update button encrypted value will be converted in to original format.


Visualforce page

<apex:page standardController="EnCrypt_Decrypt__c" extensions="EncryptExtension">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:inputField value="{!encrypt.Name}"/>
                <apex:commandButton value="Save" action="{!Save}"/>
                <apex:commandButton value="Update" action="{!test}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form> 
</apex:page>

Apex Controller

public class EncryptExtension {
    public EnCrypt_Decrypt__c encrypt{get;set;}
    //Blob cryptoKey;
    Blob cryptoKey = Blob.valueOf('380db410e8b11fa9');
    public Id recordId{get;set;}
    public EncryptExtension(ApexPages.StandardController controller) {
        //cryptoKey = Crypto.generateAesKey(256);
        recordId = Apexpages.CurrentPage().getParameters().get('id');
        if(recordId !=null){
            encrypt = [SELECT id,Name From EnCrypt_Decrypt__c 
                    WHERE id=:recordId];
        }
        else{
            encrypt = new EnCrypt_Decrypt__c();
        }
    }
    
    public PageReference Save(){
         
         Blob data = Blob.valueOf(encrypt.Name);
         Blob encryptedData = Crypto.encryptWithManagedIV('AES128', cryptoKey , data );
         String b64Data = EncodingUtil.base64Encode(encryptedData);
         encrypt.name = b64Data ;
         
         insert encrypt;
         return null; 
    }
    public PageReference test(){
         
         //Blob cryptoKey = Crypto.generateAesKey(256);
         //Blob data = Blob.valueOf(encrypt.Name);
         Blob data = EncodingUtil.base64Decode(encrypt.Name);
         Blob decryptedData = Crypto.decryptWithManagedIV('AES128', cryptoKey , data);
         String dryptData = decryptedData.toString();
         System.debug('Printing dryptData '+dryptData);
         
         encrypt.name = dryptData;
         
         update encrypt;
         return null; 
    }
}

Referece Link: http://salesforce.stackexchange.com/questions/25636/how-to-encrypt-and-decrypt-a-string-in-apex-using-the-crypto-class

Friday, 17 October 2014

Salesforce: Object Key Prefix

For Salesforce administrators and developers with years of experience work in Salesforce area, all of us should know 0015000000tCKZx is an Account record while 00350000023hJC0 is a Contact. You can easily note this in the web page URL. This also serve as record Id whether as 15 or 18 characters. Looking the first 3 characters prefix, we can  determine what is the object behind that record in both Standard and Custom object.

               

Standard Object
For standard object, all the prefix is the same. Refer the following blogs for each Standard object with the correspondence prefix:

Custom Object
Each custom object have unique prefix for each instance. You can notice it in the URL when open the record or click custom object tab for that object. Here a blog written sometimes back to get a tab view without have to create custom object tab - Hidden Tab for Custom Object

But, if the object just created and no tab is create for it, you would be a little difficult to get the prefix as it is not state anywhere in Salesforce. Here is the workaround - use a free tool Developer Workbench

Once you login, go to Standard and Custom Objects menu, select the object from dropdown and look for keyPrefix, see screenshot below: 

Another use case, you have a Salesforce record Id, but do not know what is the object for that record Id. Go through each object using Developer Workbench is way too hard. Use Developer Console with simple apex script will easily find the object. Click your name in Salesforce then click Developer Console


Once Developer Console open, click Debug then Open Execute Anonymous Window


It will show last apex code executed (if any), change the code to following and click Executebutton.

System.debug(System.LoggingLevel.ERROR, Id.valueOf('01Q50000000IhVI').getSObjectType());


See the highlight, 01Q50000000IhVI is a record for Competitor__c custom object.

Using Developer Console also can find prefix as we did using Developer Workbench, use following apex code: 
Schema.DescribeSObjectResult r =CustomObject__c.sObjectType.getDescribe();
String keyPrefix = r.getKeyPrefix();
System.debug('Printing --'+keyPrefix );

Change CustomObject__c to your real object API name. Here is the result:



RegEx to validate Salesforce Id
If you familiar with RegEx, here is the regex to validate Salesforce Id 
a-zA-Z0-9]{15,18}

Friday, 12 September 2014

Salesforce-to-Salesforce (S2S) Integration

              S2S allows you to share data between Force.com organizations.The data exchange takes place entirely within the servers that run the Force.com platform.It can be valuable for business-to-business scenarios such as partner relationship management and customer support, providing a point-and-click solution for information sharing that can be set up and managed without additional technology products and their associated costs and complexity.

salesforce to salesforce

Establishing a Connection:
         To start, you need at least two separate Force.com organizations.You already have one, so sign up for a second Developer Edition account.Then, enable the S2S feature in both organizations.
1. App Setup area and clicking Customize--> Salesforce to Salesforce-->Settings. Click the Enable check box and then the Save button.

salesforce to salesforce integration

2. S2S establishes connections between organizations using ordinary email.The process begins with one organization initiating the connection. Initiation requires a Contact record containing the email address of the person who is authorized to accept the connection on behalf of his organization. Users without Modify All Data permission cannot initiate and accept S2S connections unless an administrator has enabled the Manage Connections permission on their profiles.
3. Create a new Contact record in your first Force.com organization with the email address of the administrator of your second Force.com organization.
Note: Connections tab is only visible if you have enabled S2S in your organization.
4. Goto the all tabs then select Connections tab then create a new contact record. 

Connections tab

5. Select the Contact and click the Save & Send Invite button to send the invitation email.

New_invitation

6. Then another organization(sfdc gurukul) get email like this, 


Click on the link, Then it will asks Login details of your's.Enter login details then it will asks Accept  or Decline.

s2s_conformation

  7. Click on Accept, to Connection Activated message will appear.
Connection_Activated

Now Configuring of connection is done.

Configuring Shared Objects:
          An object is shared between two organizations when one has published it and another has subscribed to it. Publishing and subscribing are configured per object.All custom objects are supported, but not all standard objects.
1. On the connection detail page, click the Publish/Unpublish button to edit the list of the objects that are published to the connection.
 Publishing_objects

 2. Select objects to publish. To share a record, you must forward it to a connection using the External Sharing related list. After a record is shared, updates are sent automatically.

Published_objects

3. Publishing is also configured at the field level. Initially only the standard Name field is published.To add more fields, click the Edit link beside the published object.

s2s_Published_objects

4. Then select the fields  check boxes, then select save.

published_Fields

5. You’ve finished publishing the object and its fields, but records cannot be forwarded until the other organization closes the loop by subscribing to the objects. Subscribing involves mapping the published object, fields, and values so that the published records have a place to call home in the subscribing organization.
6. Log in to the second organization and visit the Connections tab.Then click on Subscribe/Unsubscribe button.

Objects_mapping

7. Each object published by the first organization is listed on the leftmost column, with a drop-down list of objects in the second organization that can be mapped to the published data.The auto-accept option streamlines the data sharing process, instructing Force.com to accept every record of the selected object forwarded by the first organization. By default, acceptance is a manual process of logging in and clicking a button.You cannot auto-accept records in child objects in Master-Detail relationships, because they cannot be accepted or rejected independently of their parent records.

Add_or_Remove_Subscribed_Objects

8. Like publishing, subscribing takes place at the field level. Click the Edit link beside the subscribed object to edit the field mappings.

Subscribed_objects

9. The left column contains the fields from the published object; the right, column drop-down lists of fields from the subscribed object. Select a field from the subscribed object to map it or click the Automatically map fields check box to map identical field names from the published object to the subscribed object.

Edit_Subscribed_Fields
10. Now you’re ready to share records.

Sharing Records:
          To share records between the organizations, the organization publishing the object forwards one or more records of that object.The subscribing organization accepts the records, which creates them in the subscribed object, mapping their fields and picklist values as configured in the Connections tab. Records are forwarded using the External Sharing related list.This special S2S related list is not visible on page layouts until manually added by an administrator.
1. Editing the page layout of the Account object to drag the External Sharing related list from the Related Lists palette at the top of the screen to the region at the bottom of the screen.


2. Click on Account object and open the record scroll to the External Sharing related list. Click the Forward This Account button.

Forward_this_account


Here you can pick one or more S2S connections to share records.

Forward_accounts
3. After forwarding the record, examine the External Sharing related list for the current status. If the subscribing organization has enabled auto-acceptance of records for this object, the status immediately indicates that the record is active. If not, the record is not active until the subscribing organization manually accepts it.

Sharing

 4. Then go to the other organization click on account tab to find Accounts from Connections section.

Accounts_from_Connections

5. Click on go button.you can view the received records,then click on accept to get it.

received_records


6. Now go to Account object to view the records.

            You have successfully caused a record to travel between two Force.com organizations. If the second organization modifies the shared record, the changes do not propagate back to the first organization. Furthermore, if the first organization modifies the record, the corresponding record in the second organization is updated to match, overwriting any updates made by the second organization. Deleting the record in either organization simply breaks the connection rather than cascading the deletion to the other organization. Sharing of the record can be stopped at any time by a click of the Stop Sharing link in the External Sharing related list.
             Although S2S maps records in a lookup relationship as strings rather than full related objects, it does provide some special functionality for Master-Detail relationships. All child records are automatically forwarded initially, when the parent record is forwarded. Updates of those original child records are also forwarded, but not additions and deletions. 

Wednesday, 10 September 2014

XML Parsing Using DOM Parser in Apex.

Use the XmlNode class to work with a node in an XML document. The DOM represents an XML document as a hierarchy of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children.
Node Types
There are different types of DOM nodes available in Apex. XmlNodeType is an enum of these different types. The values are:
COMMENT
ELEMENT
TEXT
It is important to distinguish between elements and nodes in an XML document. The following is a simple XML example:
<name>
    <firstName>Murali</firstName>
    <lastName>Mohan</lastName>
</name>
This example contains three XML elements: name, firstName, and lastName. It contains five nodes: the three name, firstName, and lastName element nodes, as well as two text nodes—Murali and Mohan. Note that the text within an element node is considered to be a separate text node.

Example to Parse the xml data or file Dynamically

VF Page :


<apex:page controller="Xmlparsercls" sidebar="false">

    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Parse Xml" action="{!Parsexml}"/>    
                <apex:commandButton value="ParseXML File" action="{!Parsexmlfile}"/>
            </apex:pageBlockButtons>
            <apex:inputTextArea value="{!xmlstring}" style="width:336px;height:260px;"/> &nbsp;&nbsp;
            <apex:inputTextArea value="{!outxmlstring}" style="width:336px;height:260px;" id="response"/><br/>

            <apex:outputLabel value="Select Xml File" for="file"/>
            <apex:inputFile fileName="{!fileName}" value="{!body}"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>


Controller :

public  class Xmlparsercls {
    public String xmlstring{get;set;}
    public String outxmlstring{get;set;}
    public String filename{get;set;}
    public blob body{get;set;}
    public Xmlparsercls(){
    }

//Parsing xml what you entered in the left text area
    public pagereference Parsexml(){
       outxmlstring ='';
       DOM.Document xmlDOC = new DOM.Document(); 
       xmlDOC.load(xmlstring); 
       DOM.XMLNode rootElement = xmlDOC.getRootElement();
       String result= walkThrough(rootElement);
       return null;
    }
  
  //This is for parsing xml file what you selected
  public pagereference Parsexmlfile(){
       outxmlstring ='';
       DOM.Document xmlDOC = new DOM.Document(); 
       xmlstring=body.tostring();
       system.debug('****xmlstring'+xmlstring);
       xmlDOC.load(xmlstring); 
       DOM.XMLNode rootElement = xmlDOC.getRootElement();
       String result= walkThrough(rootElement);
       return null;
    }
    
   Public String walkThrough(DOM.XMLNode node) {
        String result = '\n';
        if (node.getNodeType() == DOM.XMLNodeType.COMMENT) {
            return 'Comment (' +  node.getText() + ')';
        }
        if (node.getNodeType() == DOM.XMLNodeType.TEXT) {
            return 'Text (' + node.getText() + ')';
        }
        if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) {
            
            if (node.getText().trim() != '') {
                outxmlstring += node.getName()+'=' +node.getText().trim()+'\n';
                String nName = node.getName();
            /*    if(nName == 'XXX')
                  {
                             String xxx = node.getText().trim();
                   }    */
            }
            if (node.getAttributeCount() > 0) { 
                for (Integer i = 0; i< node.getAttributeCount(); i++ ) {
                    result += ', attribute #' + i + ':' + node.getAttributeKeyAt(i) + '=' + node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i));
                }  
            }
            for (Dom.XMLNode child: node.getChildElements()) {
                result += walkThrough(child);
            }
            return result;
        }
        return '';
    }
}

OUTPUT :



When you are selecting file then click on ParseXML file button.
When you type as shown above in the textarea then click on "Parse Xml" button then you can parse the xml.