DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
  • submit to reddit

XML Snippets

  • ElementTree
  • XML
  • Python
                    ElementTree is becoming python's standard XML framework.
It also supports processing data as it coming/loading.
<code>
import cElementTree

for event, elem in cElementTree.iterparse(file):
    if elem.tag == "record":
        ... process record element ...
        elem.clear()
</code>                
  • DataSet
  • XML
  • C
                    Following code will give you the XML representation of the data stored in the DataSet.

<code>

    DataSet mydataSet = new DataSet();
    DataTable table = dataSet.Tables.Add("Items");
    mytable.Columns.Add("studentid", typeof(int));
    mytable.Columns.Add("name", typeof(string));
    mytable.Rows.Add(1,'mac');
    mytable.Rows.Add(2,'jac');
    mydataSet.GetXml()
</code>                
  • parser
  • XML
  • Blackberry
  • Development
  • jacsdev
                    Hi, i use this class for pull XML from remote host

<code>
package com.jacsdev.test

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;

class GetRemoteXML extends Thread
{
	public String myUrl = "";
	
	public GetRemoteXML(String url) {
		myUrl = url;
	}
	
    public void run()
    {
          ConnectionFactory mCFactory = new ConnectionFactory();
          ConnectionDescriptor connDesc;
          connDesc = mCFactory.getConnection(myUrl);
          if (connDesc != null)
          {
              HttpConnection mHttpConn;
              mHttpConn = (HttpConnection)connDesc.getConnection();
     
              try
              {
            	  DataInputStream dis = new DataInputStream(mHttpConn.openInputStream()); 
            	  int mBytes = dis.available();
            	  ByteArrayOutputStream mByteArray = new ByteArrayOutputStream();
            	  while ( 0 < mBytes  ) 
            	  {
            		  byte[] response = new byte[mBytes];
            		  dis.read(response);
            		  mByteArray.write(response);
            		  mBytes = dis.available();
            	  }
            	  // This String contains the xml
            	  final String XmlString = mByteArray.toString();
            	  
                  UiApplication.getUiApplication().invokeLater(new Runnable()
                  {
                      public void run()
                      {
                    	  // Here show an alert on mainscreen with xml content as string
                    	  Dialog.alert(XmlString.toString());
                      }
                   });
               } 
               catch (IOException e) 
               {
            	 System.out.println("IOException: " + e.toString());
                 System.err.println("Caught IOException: " + e.getMessage());
               }
          }
    }
}
</code>

So, here the way i call it


<code>
package com.jacsdev.test;

import net.rim.device.api.ui.UiApplication;

public class MyApp extends UiApplication
{
    public static void main(String[] args)
    {
        MyApp theApp = new MyApp();       
        theApp.enterEventDispatcher();
    }
    
    public MyApp()
    {        
    	MyScreen screen = new MyScreen();
        pushScreen(screen);
        GetRemoteXML  mXML = new GetRemoteXML("http://yourserver.com/yourxmlfile.xml");
	mXML.start();
    }  
    // If  you get success , you'll see a dialog wiht xml string ... so, you must to parser it the way you want
}

</code>
@jacsdev                
  • hibernate
  • dialect
  • Oracle
  • XML
  • XMLType
                    <code>
package your.package;

import org.hibernate.dialect.Oracle10gDialect;

public class OracleDialectWithXmlSupport extends Oracle10gDialect {

   public OracleDialectWithXmlSupport() {
      super();
      registerHibernateType(oracle.xdb.XMLType._SQL_TYPECODE, "xmltype");
      registerColumnType(oracle.xdb.XMLType._SQL_TYPECODE, "xmltype");
   }
}
</code>                
  • PHP XML web services
                    // description of your code here

<code>
// insert code here..
<InitiateTransactionRequest
xmlns="http://schemas.datacontract.org/2004/07/Centricom.POLi.Services.MerchantAPI.Contract
s" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AuthenticationCode>xxxxxxxx</AuthenticationCode>
<Transaction
xmlns:dco="http://schemas.datacontract.org/2004/07/Centricom.POLi.Services.MerchantAPI.DCO"
>
<dco:CurrencyAmount>15.00</dco:CurrencyAmount>
<dco:CurrencyCode>AUD</dco:CurrencyCode>
<dco:MerchantCheckoutURL>http://mnhometeamleads.com/demo/test/xml/</dco:MerchantCheckoutURL>
<dco:MerchantCode>xxxxxxx</dco:MerchantCode>
<dco:MerchantData>MerchantDataAssociatedWithTransaction</dco:MerchantData>
<dco:MerchantDateTime>2008-08-18T14:01:02</dco:MerchantDateTime>
<dco:MerchantHomePageURL>http://mnhometeamleads.com/demo/test/xml/</dco:MerchantHomePageURL>
<dco:MerchantRef>MerchantReferenceAssociateWithTransaction</dco:MerchantRef>
<dco:NotificationURL>http://mnhometeamleads.com/demo/test/xml/notification</dco:NotificationURL>
<dco:SelectedFICode i:nil="true" />
<dco:SuccessfulURL>http://mnhometeamleads.com/demo/test/xml/successful</dco:SuccessfulURL>
<dco:Timeout>1000</dco:Timeout>
<dco:UnsuccessfulURL>http://mnhometeamleads.com/demo/test/xml/unsuccessful</dco:UnsuccessfulURL>
<dco:UserIPAddress>65.2.45.1</dco:UserIPAddress>
</Transaction>
</InitiateTransactionRequest>

		$url='https://merchantapi.apac.paywithpoli.com/MerchantAPIService.svc/Xml/transaction/initiate';   
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
        curl_setopt($curl, CURLOPT_POSTFIELDS, $xml);

        $response = curl_exec($curl);
		$response=str_replace('<a:','<',$response);$response=str_replace('</a:','</',$response);
		$result = simplexml_load_str
</code>
This is all i can made but did't work so need help..!!                
  • XSLT
  • XML
  • windows
  • web
  • URL
  • Unix
  • time
  • Text
  • String
  • SQL
  • Sinatra
  • shell
  • series60
  • rubyonrails
  • Ruby
  • rscript
  • rexml
  • regex
  • REBOL
  • raoni
  • Rails
  • Python
  • php
  • Perl
  • OSX
  • MySQL
  • math
  • Linux
  • jsfromhell
  • JOnAS
  • javascript
  • java
  • image
  • http
  • html
  • hash
  • Google
  • find
  • file
  • date
  • Database
  • css
  • csharp
  • convert
  • C++
  • C
  • bash
  • Array
  • apache
  • ActiveRecord
                    // Month Day Year Smart Dropdowns

<code>
function mdy($mid = "month", $did = "day", $yid = "year", $mval, $dval, $yval)
	{
		if(empty($mval)) $mval = date("m");
		if(empty($dval)) $dval = date("d");
		if(empty($yval)) $yval = date("Y");
		
		$months = array(1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May", 6 => "June", 7 => "July", 8 => "August", 9 => "September", 10 => "October", 11 => "November", 12 => "December");
		$out = "<select name='$mid' id='$mid'>";
		foreach($months as $val => $text)
			if($val == $mval) $out .= "<option value='$val' selected>$text</option>";
			else $out .= "<option value='$val'>$text</option>";
		$out .= "</select> ";

		$out .= "<select name='$did' id='$did'>";
		for($i = 1; $i <= 31; $i++)
			if($i == $dval) $out .= "<option value='$i' selected>$i</option>";
			else $out .= "<option value='$i'>$i</option>";
		$out .= "</select> ";

		$out .= "<select name='$yid' id='$yid'>";
		for($i = date("Y"); $i <= date("Y") + 2; $i++)
			if($i == $yval) $out.= "<option value='$i' selected>$i</option>";
			else $out.= "<option value='$i'>$i</option>";
		$out .= "</select>";
		
		return $out;
	}
</code>
                
  • XML
  • XSL
  • replace
  • XSLT
  • find
                    // description of your code here
//This XSL will search inside certain nodes of a given XML file
//for certain values and replace them.
//In my example I have a UnitOfMeasure node that contains "EA" or "FT" but I want to change
//the EA to 1 and the FT to 0.
//Also in my ObsoleteIndicator node I want to replace OBS with 1 and this other value I don't care about, 
//DNR to empty string to basically remove it.
//So we end up with the exact same XML we started with just with those values translated.
//You could do the same with regular string.replace but it would be very slow for large XML files
//as it would have to visit every character in the entire file each time you called it (in my case
// four times.)

<code>
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="node()|@*">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

<xsl:template match="//UnitofMeasure">
	<xsl:element
	name="{name(.)}">

		<xsl:choose>
			<xsl:when test="contains(string(.),'EA')">
				<xsl:value-of select="translate(string(.), 'EA', '1')" />
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="translate(string(.), 'FT', '0')" />	
			</xsl:otherwise>
		</xsl:choose>
	
	</xsl:element>
</xsl:template>

<xsl:template match="//ObsoleteIndicator">
	<xsl:element
	name="{name(.)}">
	
		<xsl:choose>
			<xsl:when test="contains(string(.),'OBS')">
				<xsl:value-of select="translate(string(.), 'OBS', '1')" />
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="translate(string(.), 'DNR', '')" />	
			</xsl:otherwise>
		</xsl:choose>
		
	</xsl:element>
</xsl:template>

</xsl:stylesheet>
</code>                
  • c sharp
  • Microsoft
  • Excel
  • XML
                    // Exports a tabular worksheet from Excel to an XMLDocument in C#

<code>
        /// <summary>
        /// Returns the given Excel file as an XML document object.
        /// If the firstRowIsHeader flag is TRUE then it will read
        /// the first row as column names and it will reflect as each
        /// XML node name.
        /// </summary>
        /// <param name="pathToExcelFile">full path including file name to Excel file</param>
        /// <param name="firstRowIsHeader">set to true if first row contains column names</param>
        /// <returns></returns>
        private static XmlDocument GetExcelAsXMLDoc(string pathToExcelFile, bool firstRowIsHeader)
        {
            DataSet excelAsDataset = GetExcelAsDataSet(pathToExcelFile, firstRowIsHeader);
            string inputXML = excelAsDataset.GetXml();
            XmlDocument returnDoc = new XmlDocument();
            returnDoc.LoadXml(inputXML);
            return returnDoc;
        }
 
	  /// <summary>
        /// Returns the first sheet in the workbook contained in the given Excel fileName
        /// as a DataSet.
        /// </summary>
        /// <param name="fileName">full path including file name for input Excel file</param>
        /// <param name="firstRowIsHeader">set to true if first row contains header field names</param>
        /// <returns></returns>
        private static DataSet GetExcelAsDataSet(string fileName, bool firstRowIsHeader)
        {
            Application oXL;
            Workbook oWB;
            Worksheet oSheet;
            Range oRng;
            try
            {
                //  creat a Application object
                oXL = new ApplicationClass();
                //   get   WorkBook  object
                oWB = oXL.Workbooks.Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                        Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                        Missing.Value, Missing.Value);

                //   get   WorkSheet object 
                oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[1];
                System.Data.DataTable dt = new System.Data.DataTable("RowItem");
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                DataRow dr;

                StringBuilder sb = new StringBuilder();
                int jValue = oSheet.UsedRange.Cells.Columns.Count;
                int iValue = oSheet.UsedRange.Cells.Rows.Count;
                //  get data columns
                for (int j = 1; j <= jValue; j++)
                {
                    dt.Columns.Add("column" + j, System.Type.GetType("System.String"));
                }
                
                //  get data in cell.
                // If the user set the firstRowIsHeader flag then save these cell values
                // as column names instead of actual row values.
                for (int i = 1; i <= iValue; i++)
                {
                    dr = dt.NewRow();
                    for (int j = 1; j <= jValue; j++)
                    {
                        oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j];
                        string strValue = oRng.Text.ToString();

                        if (firstRowIsHeader && i == 1)
                        {
                            dt.Columns[j-1].Caption = strValue;
                        }
                        else
                        {
                            dr["column" + j] = strValue;
                        }
                        
                    }

                    //don't add an empty row if we are just reading in header field names
                    if ( ! (firstRowIsHeader && i == 1) )
                    {
                        dt.Rows.Add(dr);
                    }                    
                }

                //now rename the column names to the header field names
                //if the user said the first row was a header.
                if (firstRowIsHeader)
                {
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        dt.Columns[k].ColumnName = (dt.Columns[k].Caption.Replace(" ",""));
                    }
                }

                return ds;
            }
            catch (Exception ex)
            {
                //log or print your exception!
                return null;
            }
            finally
            {
                //clean up file handles and objects
            }
        }

</code>                
  • activesupport
  • XML
  • JSON
  • Ruby
                    // Convert XML to JSON using Ruby and ActiveSupport

<code>
#! /usr/bin/env ruby

require 'rubygems'
require 'active_support/core_ext'
require 'json'

xml = File.open(ARGV.first).read
json = Hash.from_xml(xml).to_json

File.open(ARGV.last, 'w+').write json
</code>                
  • netbeans
  • XML
  • java
                    // Crea un archivo .bat para una aplicación Java construida desde NetBeans. Agregar este tag en build.xml

<code>
    <target name="-post-jar">        
       <echo file="${dist.dir}/run.bat">java -jar ${application.title}.jar</echo>    
    </target> 
</code>