XML Reading Using Java Servlet

I need some help in reading xml file using java servlet.
May i have some sample codes to read xml files?
I would really appreciate your help. Thanks!!!

This grabs a url and parses it with a servlet.
URL befreeUrl = new URL(urlString);
uri = new URI(urlString);
URLConnection yc = befreeUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
factory.setValidating(true);
out = new OutputStreamWriter(System.out, "UTF8");
DefaultHandler handler = new BeFreeRequestSAXParser(); /* custom handler class */;
parser.parse(uri.toString(), handler);
in.close();

Similar Messages

  • How to read the data from Excel file and Store in XML file using java

    Hi All,
    I got a problem with Excel file.
    My problem is how to read the data from Excel file and Store in XML file using java excel api.
    For getting the data from Excel file what are all the steps i need to follow to get the correct result.
    Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
    Thanks & Regards,
    Sreenu,
    [email protected],
    india,

    If you want someone to do your work, please have the courtesy to provide payment.
    http://www.rentacoder.com

  • Long running reports using java servlets

    Hello,
    I'm running into a problem using java servlets to produce database reports and sending them back to the client browser as excel or html. The problem comes into play when the user has submitted two reports then goes to run a third and the browser hangs. I realized now that this is because of the two active connections that the user already has to the app server. Does anyone have any suggestions on how to get around this? I'm trying to now write the report to the server, and provide the browser with a url, but it seams as though the connection isn't totally closed even though I close the response printwriter.... Any suggestions would be greatly appreciated....

    Unfortunately I dont have an answer to your question, but:
    If the reports are large/long running, should they be generated on demand? You could schedule the reports to be generated every day, month or whenever appropriate, stored on the server and then quickly pulled by the user whenever needed.

  • How to write as XML file using java 1.5

    hi all,
    i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
    can any body help me out to solve this issue.......
    thankx in advance
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.DocumentHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.ParserFactory;
    import java.io.*;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                   
                   dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();                   
    Document xmlDoc =  db.newDocument();
    // this creates the xml document ref
    // parent node reference
    Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
    // root node
    xmlDoc.appendChild(rootnd);
    Element rownd = (Element) xmlDoc.createElement("ROW");
    rootnd.appendChild(rownd);
    Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
    rownd.appendChild(statusnd);
    statusnd.appendChild(xmlDoc.createTextNode("Y")
    FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
    Writer outf = new OutputStreamWriter(outpt, "UTF-8");
    //error is occuring here Since write method is not available in the Document class
    xmlDoc.write(outf);
    outf.flush();

    Hi,
    when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
    However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this:     TransformerFactory tf = TransformerFactory.newInstance();
         // set all necessary features for your transformer -> see OutputKeys
         Transformer t = tf.newTransformer();
         t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
    Hope it helps.

  • Merging 2 message history xml files using java

    hi., i'm new to xml programming..
    well..., i got homework bout it..., and got a lot of problems to write it..
    could you help me a favor??
    I need to write a homework bout merging 2 MSN mssg history files (xml files) using java.
    At least need to maintain their date, time, sender, receiver, and information(sayings)....and are ordered using time..
    can u help me??

    Well, show us what you've got and where you are having difficulty.

  • Connecting Pooling using Java Servlets

    Hello Friends I am in search of a programme to make a connection pooling using Java Servlets.
    Please let me know where i will get it or do post it.

    If you mean JDBC connection pools, one solution can be found here - http://www.javaexchange.com
    Chuck

  • How to read XML Values using JAVA

    Hi FRNDS,
    I uploaded one XML File in imported Archieves, i have to read the value form XML uisng JAVA code,
    using XSL able to read  like  xsl variable name='TimeZone' select =$linkDoc//...........*
    But using java i have to read the value from XML,is it possible to read the value??
    please give me some sample code.
    regards,
    Raja Sekhar

    But using java i have to read the value from XML,is it possible to read the value??
    Check the below JAVA code from help:
    http://help.sap.com/saphelp_nwpi71/helpdata/en/55/7ef3003fc411d6b1f700508b5d5211/content.htm
    you can ignore the XSLT part and configure only the JAVA code...check if this suits your needs.
    Regards,
    Abhishek.

  • Reading an XML file using Java

    Dear all,
    Currently, I'm planning to write a java program that will read from an xml file. This is my XML file:
    <?xml version="1.0"?>
    <HUMIDITYMEASURE>
    <HUMIDITY>32.0</HUMIDITY>
    </HUMIDITYMEASURE>
    Now, here is my Java code:
    import java.io.*;
    class ReadAFile{
    public static void main(String[]args){
    try{
    File myFile=new File("XMLFile.xml");
    FileReader fileReader= new FileReader(myFile);
    BufferedReader reader = new BufferedReader(fileReader);
    String line = "null";
    while ((line = reader.readLine()) !=null){
    System.out.println(line);
    reader.close();
    catch(Exception ex){
    ex.printStackTrace();
    So far the program displays the content of the xml file (with the tags). However, my aim is to make the program display the values, not the tags. For example, in this case, i'd like my program to display the value '32.0' rather than:
    <?xml version="1.0"?>
    <HUMIDITYMEASURE>
    <HUMIDITY>32.0</HUMIDITY>
    </HUMIDITYMEASURE>
    Can anyone provide me with any advice as to how i can do this please? I tried using the tokenizer and split, but to be honest, they dont really work. If anybody has any suggestions, please reply if possible.
    Regards,

    I have found the solution to my task.
    Many thanks to those who have viewed/replied to my message.
    For those of you who may be wondering how the problem was solved, it is useful to refer to some documents relating to Java and XML (as combination).
    Imported packages such as:
    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    and variations of import javax.xml were used.
    The use of Nodes and NodeLists I used to.
    Thanks again.
    p.s. More details on XML and Java are found on the Sun Website.
    Regards,
    Raheal

  • Writing an XML file using a Servlet

    Hello, I'm trying to code a servlet that receives a POST from a HTTP and output its data to a XML file, the problem is that I get the following error:
    The XML page cannot be displayed
    Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
    XML document must have a top level element. Error processing resource 'http://localhost:8080/XMLSender/xmlsend'.
    I don't know what happens, because I'm NOT trying to show the content, just to save it, I post my code here so anyone can help me, please. Thanks in advance.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class xmlsender extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream salida = res.getOutputStream();
    res.setContentType("text/xml");
    String cadenanumero = req.getParameter("numero");
    String cadenaoperadora = req.getParameter("operadora");
    String cadenabody = req.getParameter("mensaje");
    String cadenashortcode = req.getParameter("shortcode");
    File f1 = new File("salida.xml");
    FileWriter writer = new FileWriter(f1);
    writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    writer.write("<root>");
    writer.write("<tlf>" + cadenanumero + "</tlf>");
    writer.write("<op>" + cadenaoperadora + "</op>");
    writer.write("<sc>" + cadenashortcode + "</sc>");
    writer.write("<body>" + cadenabody + "</body>");
    writer.write("</root>");
    writer.close();
    }

    Yes, in fact what I want is the file to be in the server, now, I modificated my code to the following:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class xmlsender extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream salida = res.getOutputStream();
    res.setContentType("text/HTML");
    String cadenanumero = req.getParameter("numero");
    String cadenaoperadora = req.getParameter("operadora");
    String cadenabody = req.getParameter("mensaje");
    String cadenashortcode = req.getParameter("shortcode");
    File f1 = new File ("salida.xml");
    FileWriter writer = new FileWriter(f1);
    /*salida.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    salida.println("<root>");
    salida.println("<tlf>" + cadenanumero + "</tlf>");
    salida.println("<op>" + cadenaoperadora + "</op>");
    salida.println("<sc>" + cadenashortcode + "</sc>");
    salida.println("<body>" + cadenabody + "</body>");
    salida.println("</root>"); */
    salida.println("Finalizado");
    f1.createNewFile();
    writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    writer.write("<root>");
    writer.write("<tlf>" + cadenanumero + "</tlf>");
    writer.write("<op>" + cadenaoperadora + "</op>");
    writer.write("<sc>" + cadenashortcode + "</sc>");
    writer.write("<body>" + cadenabody + "</body>");
    writer.write("</root>");
    writer.close();
    It still do not create my file "salida.xml", still don't know why. Any help is welcome.

  • How to display an xml file using a servlet with the styles given in an XSL

    Dear Developer...
    i have xml and xsl files.
    Now i want to display the html output produced by the xsl and xml using a servlet...give me any samplecode.

    ... except for the "using XSLT" part. But that doesn't make sense anyway because XSLT doesn't display anything, it just transforms data.

  • How to search and replace in an xml file using java

    Hi all,
    I am new to java and Xml Programming.
    I have to search and replace a value Suresh with some other name in the below xml file.
    Any help of code in java it is of great help,and its very urgent.
    I am using java swings for generating two text boxes and a button but i am not able to search in the xml file thru the values that are entered into these text boxes.
    Thanks in advance.
    **XML File*
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <student>
    <stud_name>Suresh</stud_name>
    <stud_age>40</stud_age>
    </student>Also i am using SAX Parser in the java program
    any help of code or any tutorials for sax parisng is very urgent please help me to resolve this problem
    Edited by: Karthik84 on Aug 19, 2008 1:45 AM
    Edited by: Karthik84 on Aug 19, 2008 3:15 AM

    Using XPath to locate the elements you are after is very easy.
    Try something like this:
    import java.io.File;
    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 javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    public class BasicXMLReplaceWithDOM4J {
         static String inputFile = "C:/student.xml";
         static String outputFile = "C:/studentRenamed.xml";
         public static void main(String[] args) throws Exception {
              // Read xml and build a DOM document
              Document doc = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder().parse(new InputSource(inputFile));
              // Use XPath to find all nodes where student is named 'Suresh'
              XPath xpath = XPathFactory.newInstance().newXPath();
              NodeList nodes = (NodeList)xpath
                   .evaluate("//stud_name[text()='Suresh']", doc, XPathConstants.NODESET);
              // Rename these nodes
              for (int idx = 0; idx < nodes.getLength(); idx++) {
                   nodes.item(idx).setTextContent("Suresh-Renamed");
              // Write the DOM document to the file
              Transformer xformer = TransformerFactory.newInstance().newTransformer();
              xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
    }- Roy

  • XML Validation using java for SQL Injection and script validation

    I have an input coming from xml file.
    I have to read that input and validate the input against sql injections and scripts.
    I require help now how to read this xml data and validate against the above two options.
    I am a java developer.
    in this context what is marshelling?

    http://www.ibm.com/developerworks/library/x-javaxmlvalidapi.html?ca=dgr-lnxw07Java-XML-Val
    http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/package-summary.html
    The following code validates the xml against a xml schema
    // define the type of schema - we use W3C:
    String schemaLang = "http://www.w3.org/2001/XMLSchema";
    SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
    Schema schema = factory.newSchema(new StreamSource("sample.xsd"));
    Validator validator = schema.newValidator();
    // at last perform validation:
    validator.validate(new StreamSource("sample.xml"));Message was edited by:
    haishai

  • Using Java Servlet with CSV

    Hello!!
    I would be obliged if some one could tell me anyway of using CSV (Collaborative Source Versioning) with Java Servlets. I have searched and the only package that I have found is jCSVSlet but I can't figure out how to use it. I would be obliged if anybody could point out any other packages that can be used for File Versioning or if anybody could send me any examples of JCSVSlet or any other related software.
    Saad Tawwab

    And what do you mean by "with"? Do you want to control versions of the source code of the servlets, or do you want to write a servlet to control version of the source code of something else?

  • Generic Populating the XML document using Java Class Generator and Reflection

    I am looking for a generic source code in order to convert the data parsed from any tabular text form ( tab delimited for example that maps certain XML Schema created form Database Schema for Oracle.
    I know it is possible to generate XML DTD or XSD from Oracle database table schema by XSU utility from XDK. And also it is possible to create Java source files from an XML DTD or XSD by using XML Clas Generator.
    I believe there must be some generic code that parses tabular text data and converts them to XML format using above mentioned generated Java source files and may be Java reflection mechanism.
    If anyone has any tool or knows any free ware that helps me, I would like to know about it, and I would really appreciate it.

    1. Read the XML file into a DMO object, walk the DOM to find the list, insert your new entry as a child, write the DOM back to a file.
    2. If the XML is not in a file, but in a string, then you can do the same with string input and output.

Maybe you are looking for

  • Webutil workaround with ienative??

    Hi, We had success run webutil on redhat 9 / adv server 2.1 , win32 platform with config on jinit and jpi to win32 client browser , but on ienative mode , I had repack *.jar to *.cab and resign all we need , the error classnotfound still exist, we gu

  • Installing Zenworks 7 desktop management on Windows 2008

    Hello, I tried to install Zenworks 7 sp1 Desktop Management on a Windows 2008 server running Edirectory 8.8 sp5, but I got an error message saying that the OS is not suppported. Is there anyway to install this on a Windows 2008 server ? I accidently

  • Why doesn't my "cut" audio file work?

    I tried to import an audio track to Garageband but it's a protected AAC file (purchased from iTunes) so it won't let me do it. I then tried to convert it but, of course, couldn't. Then I found this neat little thing where I can change when the song b

  • TS2776 Itunes on Windows 7 error not discussed...

    I keep getting 'This ipod (or iphone) cannot be used because required software is not installed' It tells me to redownload itunes, so I have 6 times. The message will not go away. What do I do?

  • Date of Production

    I need a MBP in time for a business/education trip in 5 days. A reputable reseller has one with the specs I'd like that I can get in 3 days. Is there anyway I can tell the date of manufacture from the Mfr#? Fron this forum I've learnt that the more r