Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Monday, February 18, 2013

Spring bean syntax




1. Import resources

Below is the syntax to import resources from various files. It is helpful when you want to bifurcated beans and database configuration in separate files and merger everything into single servlet. Here you can provide absolute or relative path of the source file.

<beans>
<import resource="file1.xml" />
<import resource="../file2.xml" />
</beans>

2. Spring MVC Dispatcher Servlet, syntax to load XMLs using init param

You can use it in web.xml file to XMLs using init param. You can load various XMLs like  beans and database configuration etc.

<web-app>
    <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>            
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/test/*.xml
            </param-value>        
        </init-param>        
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>/test/*.do</url-pattern>
    </servlet-mapping>
</web-app>

3. Url Handler Mapping syntax

Below is the example for Mapping URLs with respective beans, this is useful when you want to keep all URLs mapping together at one place.

<beans>

    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
        <props>
            <prop key="/sfc.do">simpleFormController</prop>
            <prop key="/mac.do">multiActionController</prop>
        </props>
        </property>
    </bean>


    <bean id="simpleFormController" class="com.javaxp.FormController" autowire="byName">
        <property name="commandName" value="formBean"></property>
        <property name="commandClass" value="com.javaxp.FormBean"></property>
        <property name="formView" value="form"></property>
        <property name="successView" value="submit"></property>        
    </bean>

    <bean id="multiActionController" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="action" />
<property name="defaultMethodName" value="defaultPage" />
    </bean>

</beans>

Friday, December 2, 2011

XML document structures must start and end within the same entity.

If you get below mentioned error

[Fatal Error] :1:7717: XML document structures must start and end within the same entity.
Exception in thread "main" org.xml.sax.SAXParseException: XML document structures must start and end within the same entity.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)

As the error suggest XML document is not formatted properly. Kindly go through the XML and look for any missing tags.

Indenting XML Output in Java

Here is a simple JAVA program for Indenting / Formatting a long XML string. You can provide a XML as a string OR can provide XML from a file according to your requirement.

Formatting an XML can be useful for reading or just simply pretty printing it.

Here is a complete tested code you can directly run the program and see the output.

/* IndentXML.java */

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class IndentXML {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException
    {
       
        //get the factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       
        //Using factory get an instance of document builder
        DocumentBuilder db = dbf.newDocumentBuilder();
       
        //providing XML string to be indented
       
String xmlStringToIndent = "<AllEmployee><Employee><Name>Ram</Name><Designation>Programmer</Designation><Department>Development</Department></Employee><Employee><Name>Shyam</Name><Designation>TL</Designation><Department>Finanace</Department></Employee><Employee><Name>Geeta</Name><Designation>Manager</Designation><Department>HR</Department></Employee></AllEmployee>";
       
        //converting String to InputStream
        InputStream inStr = new ByteArrayInputStream(xmlStringToIndent.getBytes());
       
        Document doc = db.parse(inStr);
       
        //Output file
        File outputFile = new File("c:/indentedOutputXmlFile.xml");
        OutputStream outSrc = new FileOutputStream(outputFile);
       
        //creating a transformer
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer  = transFactory.newTransformer();
       
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
       
        transformer.transform(new DOMSource(doc), new StreamResult(outSrc));
       
        System.out.println("OutputFile created sucessfully!! "+outputFile.getPath());

    }

}


Input XML

String xmlStringToIndent = "<AllEmployee><Employee><Name>Ram</Name><Designation>Programmer</Designation><Department>Development</Department></Employee><Employee><Name>Shyam</Name><Designation>TL</Designation><Department>Finanace</Department></Employee><Employee><Name>Geeta</Name><Designation>Manager</Designation><Department>HR</Department></Employee></AllEmployee>";


Output XML

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<AllEmployee>
     <Employee>
          <Name>Ram</Name>
          <Designation>Programmer</Designation>
          <Department>Development</Department>
     </Employee>
     <Employee>
          <Name>Shyam</Name>
          <Designation>TL</Designation>
          <Department>Finanace</Department>
     </Employee>
     <Employee>
          <Name>Geeta</Name>
          <Designation>Manager</Designation>
          <Department>HR</Department>
     </Employee>
</AllEmployee>



 Note :

If you are passing XML string and it contains double quotes ("). Make to to bypass it by adding backward slash (\").

I observer below mentioned error when the string contained space in the beginning as show below.

String xmlStringToIndent = " <AllEmployee><Employee><Name>Ram</Name><Designation>Programmer ....."

Note the space in the beginning of the string. Make sure your XML is formatted properly.

Error

[Fatal Error] :1:7: The processing instruction target matching "[xX][mM][lL]" is not allowed.
Exception in thread "main" org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
    at com.hewitt.hre.fadv.IndentXML.main(IndentXML.java:43)

Tuesday, October 20, 2009

Java : Simple XML Parser

/* SimpleXmlParser.java */

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class SimpleXmlParser
{
public static void main(String[] args)
{
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

Document dom = null;

try
{
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();

dom = db.parse("xmlFile.xml");

//get the root elememt
Element docEle = dom.getDocumentElement();

//get a nodelist of slot elements
NodeList nl = docEle.getElementsByTagName("Employee");

if(nl != null && nl.getLength() > 0)
{
for(int i = 0 ; i < nl.getLength();i++)
{
System.out.println("--Employee--");

Element el = (Element)nl.item(i);

System.out.println("Name : "+getTextValue(el,"Name"));
System.out.println("Designation : "+getTextValue(el,"Designation"));
System.out.println("Department : "+getTextValue(el,"Department"));
}
}
}
catch(Exception ex)
{
System.out.println("Exception : "+ex);
}
}

public static String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0)
{
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}

return textVal;
}
}


/* xmlFile.xml */

<AllEmployee>
<Employee>
<Name>Ram</Name>
<Designation>Programmer</Designation>
<Department>Development</Department>
</Employee>
<Employee>
<Name>Shyam</Name>
<Designation>TL</Designation>
<Department>Finanace</Department>
</Employee>
<Employee>
<Name>Geeta</Name>
<Designation>Manager</Designation>
<Department>HR</Department>
</Employee>
</AllEmployee>

Output

--Employee--
Name : Ram
Designation : Programmer
Department : Development
--Employee--
Name : Shyam
Designation : TL
Department : Finanace
--Employee--
Name : Geeta
Designation : Manager
Department : HR