Read a XML file and store an element to a String

Hello,
I'm looking for a solution to load an XML file (see below), read all elements and store the first of them (the first "description" element) in a String variable.
Should I load the file in a Node variable?
What is the best solution?
The XML file looks like:
<document>
<typeOfWorkstation >
<item id="desktop">
<description>Desktop</description>
</item>
<item id="laptop">
<description>Laptop</description>
</item>
<item id="other">
<description>Other configuration</description>
</item>
</typeOfWorkstation>
</docuement>
All suggestions will be greatly appreciated
Thank you
Sylvain

no example, uh? the tutorial is packed with code samples
this will get you started:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("c:/folder/data.xml"));

Similar Messages

  • Need to read a XML file and store multilingual data

    I am having an XML file which contains multiple records and each maybe in a different language .identified EN -english ES-Spanish etc
    - <Document xmlns="http://www.xxxxx.com/ws/integration/toolkit/2011/05">
    - <Attributes>
    <Attribute name="duration">0:00:02.993</Attribute>
    <Attribute name="count">47</Attribute>
    <Attribute name="entity">Requisition</Attribute>
    <Attribute name="mode">XML</Attribute>
    <Attribute name="version">http://www.xxxx.com/ws/tee800/2009/01</Attribute>
    </Attributes>
    - <Content>
    - <ExportXML xmlns="http://www.xxxxx.com/ws/integration/toolkit/2005/07/action/export">
    - <record>
    <field name="ContestNumber">120000002O</field>
    <field name="JobInformation,JobType,Description">Standard</field>
    <field name="JobFamily">ACCOUNTING/FINANCE</field>
    <field name="JobInformation,Organization,Name">CHMS-DO NOT USE</field>
    <field name="Country">USA</field>
    <field name="State">Illinois</field>
    <field name="City">Lake County</field>
    <field name="Title_EN">TaTest1</field>
    <field name="Title_es">TaTest1 translated to Espanol</field>
    <field name="InternalDescription_EN">Humira marketing team - develop programs.</field>
    <field name="InternalDescription_zhCN" />
    <field name="InternalDescription_zhTW" />
    <field name="InternalDescription_es">Development of marketing programs for </field>
    <field name="ExternalDescription_EN">Marketing programs for core products</field>
    <field name="ExternalDescription_zhCN" />
    <field name="ExternalDescription_zhTW" />
    <field name="ExternalDescription_es">Marketing core products - Spain</field>
    <field name="URL_en">http://[ZONE]/careersection/[CAREER_SECTION]/jobdetail.ftl?lang=en&job=120000002O</field>
    <field name="URL_zhCN" />
    <field name="URL_zhTW" />
    <field name="URL_es">http://[ZONE]/careersection/[CAREER_SECTION]/jobdetail.ftl?lang=es&job=120000002O</field>
    <field name="PostedExternally">true</field>
    <field name="PostedInternally">true</field>
    <field name="EnglishActive">true</field>
    <field name="SimplifiedChineseActive">false</field>
    <field name="TraditionalChineseActive">false</field>
    <field name="SpanishActive">true</field>
    <field name="InternalBonusTracking" />
    <field name="ExternalBonusTracking" />
    <field name="POSTING_GRADE" />
    <field name="SAP_Schedule">Full-time</field>
    <field name="PostingDateExternal">2012-11-20</field>
    <field name="PostingDateInternal">2012-11-20</field>
    </record>
    </ExportXML>
    </Content>
    </Document>
    I need to store and retrieve data into a AL32UTF8 database without losing language attributed.
    I am using DBMS_XMLDOM.getnodevalue (); to fetch the XML stored in a CLOB column
    But the package returns VARCHAR2 .How do i return NVARCHAR2 so that i can store Multilingual data
    DBMS_XMLDOM.GETNODEVALUE(
    n IN DOMNode)
    RETURN VARCHAR2;
    Or is there an easier way around using XMLTYPE
    Edited by: Rameshkumar T on Nov 27, 2012 6:14 AM

    dbms_lob.loadclobfromfile( v_xml_msg
                                          , v_xml_bfile
                                          , dbms_lob.getlength(v_xml_bfile)
                                          , v_dest_offset
                                          , v_src_offset
                                          , NLS_CHARSET_ID('AL32UTF8')
                                          , v_lang_context
                                          , v_warning
    SELECT message
       INTO   v_xml_clob
       FROM   gjb_xml_message gtmq
       WHERE  message_id = v_msg_id;
       v_line_no := 1;
       v_doc     := dbms_xmldom.newDOMDocument(v_xml_clob);
       v_line_no := 2;
       v_nodes    := dbms_xmldom.getElementsByTagName(v_doc, '*');
       FOR i IN 0..dbms_xmldom.getlength(v_nodes)-1
       LOOP
           BEGIN
               v_line_no := 3.0;
               v_element_x  := dbms_xmldom.makeelement(xmldom.item(v_nodes,i));
               v_line_no := 3.1;
               v_node       := dbms_xmldom.item(v_nodes,i);
               v_line_no := 3.2;
               v_tag        := dbms_xmldom.getNodeName(v_node);
               v_line_no := 3.3;
               v_node_2     := dbms_xmldom.getfirstchild(v_node);
               v_line_no := 4.0;
               v_node_map     := DBMS_XMLDOM.getattributes (v_node);
               FOR x in 0 ..DBMS_XMLDOM.getlength (v_node_map)- 1
               LOOP
                  BEGIN
                     v_line_no := 4.1;
                     v_one_node := DBMS_XMLDOM.item (v_node_map, x);
                     v_line_no := 4.2;
                     v_attrname := DBMS_XMLDOM.getnodename (v_one_node);
                     v_line_no := 4.3;
                     v_attrval  := DBMS_XMLDOM.getnodevalue (v_one_node);
                     IF  v_attrval = 'ContestNumber' THEN
                          v_line_no := 4.4;
                          v_contest_num := v_tag_value;
                          v_rec_no := NULL;
                          IF v_load_type = 'I' THEN
                             v_rec_no := fn_get_job_id(v_contest_num);
                          END IF;
                          IF v_rec_no IS NULL THEN
                             SELECT seq_gjbjobid.NEXTVAL
                             INTO   v_rec_no
                             FROM   dual;
                          END IF;
                     END IF;
    IF UPPER(v_tag) = 'FIELD' THEN
             BEGIN
                v_line_no := 5;
                INSERT INTO gjb_xml_data
                       ( message_id
                       , job_id
                       , tag_name
                       , col_name
                       , col_no
                       , tag_level
                       , tag_value
                       , tag_lang
                       , tag_value_clob
                SELECT v_msg_id
                     , v_rec_no
                     , tag_name
                     , col_name
                     , col_no
                     , tag_level
                     , v_tag_value
                     , tag_lang
                     , v_tag_value_clob
                FROM   gjb_xml_tags gxt
                WHERE  tag_name = v_attrval;
                v_tag_value := NULL;
                v_tag_value_clob := NULL;Edited by: Rameshkumar T on Nov 27, 2012 8:27 AM

  • Reading XML file and skip certain elements/attributes??

    Hi folks!
    Suppose I have a XML file looking like this:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE dvds SYSTEM "DTDtest.dtd">
    <dvds>
    <dvd>
    <title>
    Aliens
    </title>
    <director>
    James Cameron
    </director>
    <format>
    1.85:1
    </format>
    </dvd>
    <dvd>
    <title>
    X-Men
    </title>
    <director>
    Bryan Singer
    </director>
    <format>
    2.35:1
    </format>
    </dvd>
    </dvds>
    In my Java application I want to read this XML file and print it on the screen (including all tags etc). So far, so good. BUT, if I want to skip certain elements, i.e. all information about the dvd 'X-Men', how am I supposed to do this? In other words, I would like my app to skip reading all information about X-Men and continue with the next <dvd>... </dvd> tag. Is this possible?
    My code so far is from the XML tutorial from Sun and it looks like this:
    import java.io.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    public class MyXML extends DefaultHandler
    public static void main(String argv[]) {
    if (argv.length != 1) {
    System.err.println("Usage: cmd filename");
    System.exit(1);
    // Use an instance of ourselves as the SAX event handler
    DefaultHandler handler = new MyXML();
    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
    // Set up output stream
    out = new OutputStreamWriter(System.out, "UTF8");
    // Parse the input
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse( new File(argv[0]), handler);
    } catch (Throwable t) {
    t.printStackTrace();
    System.exit(0);
    static private Writer out;
    //===========================================================
    // SAX DocumentHandler methods
    //===========================================================
    public void startDocument()
    throws SAXException
    emit("<?xml version='1.0' encoding='UTF-8'?>");
    nl();
    public void endDocument()
    throws SAXException
    try {
    nl();
    out.flush();
    } catch (IOException e) {
    throw new SAXException("I/O error", e);
    * <p>This method prints the start elements including attr.
    * @param namespaceURI
    * @param lName
    * @param qName
    * @param attrs
    * @throws SAXException
    public void startElement(String namespaceURI,
    String lName, // local name
    String qName, // qualified name
    Attributes attrs)
    throws SAXException
    String eName = lName; // element name
    if ("".equals(eName)) eName = qName; // namespaceAware = false
    emit("<"+eName);
    if (attrs != null) {
    for (int i = 0; i < attrs.getLength(); i++) {
    String aName = attrs.getLocalName(i); // Attr name
    if ("".equals(aName)) aName = attrs.getQName(i);
    emit(" ");
    emit(aName+"=\""+attrs.getValue(i)+"\"");
    emit(">");
    public void endElement(String namespaceURI,
    String sName, // simple name
    String qName // qualified name
    throws SAXException
    emit("</"+qName+">");
    * <p>This method prints the data between 'tags'
    * @param buf
    * @param offset
    * @param len
    * @throws SAXException
    public void characters(char buf[], int offset, int len)
    throws SAXException
    String s = new String(buf, offset, len);
    emit(s);
    //===========================================================
    // Utility Methods ...
    //===========================================================
    // Wrap I/O exceptions in SAX exceptions, to
    // suit handler signature requirements
    private void emit(String s)
    throws SAXException
    try {
    out.write(s);
    out.flush();
    } catch (IOException e) {
    throw new SAXException("I/O error", e);
    // Start a new line
    private void nl()
    throws SAXException
    String lineEnd = System.getProperty("line.separator");
    try {
    out.write(lineEnd);
    } catch (IOException e) {
    throw new SAXException("I/O error", e);
    Sorry about the long listing... :)
    Best regards
    /Paul

    A possibility that comes to mind is to create an XSLT script to do whatever it is you want - and call it from inside the program. The XSLT script can be stashed inside your .jar file by using getClass().getClassLoader().getResource("...")
    - David

  • Reading A xml file and sending that XML Data as input  to a Service

    Hi All,
    I have a requirement to read(I am using File adapter to read) a xml file and map the data in that xml to a service(schema) input variable.
    Example of  xml file that I have to read and the content of that xml file like below:
      <StudentList>
        <student>
           <Name> ravi</Name>
           <branch>EEE</branch>
          <fathername> raghu</fathername>
        </student>
      <student>
           <Name> raju</Name>
           <branch>ECE</branch>
          <fathername> ravi</fathername>
        </student>
    <StudentList>
    I have to pass the data(ravi,EEE,raghu etc) to a service input varible. That invoked Service input variable(schema) contains the schema similar to above schema.
    My flow is like below:
      ReadFile file adapter -------------------> BPEL process -----> Target Service.I am using transform activity in BPEL process to map the data from xml file to Service.
    I am using above xml file as sample in Native Data format(to create XSD schema file).
    After I built the process,I checked file adapter polls the data and receive the file(I am getting View xml document in EM console flow).
    But transform activity does not have anything and it is not mapping the data.I am getting blank data in the transform activity with only element names like below
    ---------------------------------------------------------------------------EM console Audit trail (I am giving this because u can clearly understand what is happening-----------------------------------------------------
       -ReceiveFile
            -some datedetails      received file
              View XML document  (This xml contains data and structure like above  xml )
        - transformData:
            <payload>
              <InvokeService_inputvariable>
                  <part name="body">
                     <StudentList>
                         <student>
                           <name/>
                            <branch/>
                            <fathername/>
                         </student>
                   </StudentList>
              </part>
             </InvokeService_inputvariable>
    'Why I am getting like this".Is there any problem with native data format configuration.?
    Please help me out regarding this issue as I am running out my time.

    Hi syam,
    Thank you very much for your replies so far so that I have some progrees in my task.
    As you told I could have put default directory in composite.xml,but what happenes is the everyday new final subdirectory gets created  in the 'soafolder' folder.What I mean is in  the c:/soafolder/1234_xmlfiles folder, the '1234_xmlfiles' is not manually created one.It is created automatically by executing some jar.
    Basically we can't know the sub folder name until it is created by jar with its own logic. whereas main folder is same(soafolder) ever.
    I will give you example with our folder name so that it would be more convenient for us to understand.
    1) yesterday's  the folder structure :  'c:/soafolder/130731_LS' .The  '130731_LS' folder is created automatically by executing some jar file(it has its own logic to control and create the subdirectories which is not in our control).
    2) Today's folder structure :  'c:/soafolder/130804_LS. The folder is created automatically(everytime the number part(130731,130804).I think that number is indicating 2013 july 31 st like that.I have to enquire about this)is changing) at a particular time and xml files will be loaded in the folder.
    Our challenge : It is not that we can put the default or further path in composite.xml and poll the file adapter.Not everytime we have to change the path in composite.xml.The process should know the folder path (I don't know whether it is possible or not.) and  everyday and file adapter poll the files in that created subfolders.
    I hope you can understand my requirement .Please help me out in this regard.

  • Read a property file and store it in a hashmap

    Hi,
    I have tried to read a property file and store it in a hashmap. The property-names should be stored in keys and the property-values (after = symbol) in values of the hashmap. any ideas? Is it possible to do this?

    mandy2001ir wrote:
    yes, but I need the hashmap for another reason. Actually I'm trying to use the properties file to have a dynamic hachmap. I don't want to change the code anytime I want to put a value in the hashmap. therefor I write the "keys" and "values" in a property file and change the property file. That's the reasn why we have property files, isn't it?What's a "dynamic hashmap"? There's no other kind! Whenever someone starts bandying around the word "dynamic" in contexts like this, it usually means there's a simple solution to their problem, that they haven't yet considered, or mistakenly don't believe is applicable to them, because of this "unique" need for something "dynamic". Trust me, you just need to load the file using a Properties object, and you're done. Properties extends Hashtable, which is virtually the same thing as a HashMap. Properties does exactly what you want it to. it's the very reason the class exists
    Have you even looked at the javadoc for java.util.Properties yet? I'm betting not, because if you had, you'd know exactly what I meant. And since you haven't, I'm at a bit of a loss as to how you can so easily dismiss the class as useless, despite existing to do exactly what you need

  • Reading the datas in the Xml file  and store it in the array using java

    Hi every one
    Can any one send me the java coding for traversing through XML file and get the data and store it in the array (SAX parser is prefered)
    its a urgent requirement . please help me
    Regards
    Arun

    i send it to ur mail id ,
    could you please send me a mail to [email protected]

  • Read in XML file and spit out specific element

    Hi all i wonder if someone could give me a hand. I've got some code (below) which reads in an xml file and spits out the contents of the file. Thats fine and dandy, however what i want to be able to do is specify which element to spit out, which i'm not sure how to do. So say i had the following xml file:
    <?xml version="1.0"?>
    <OpenSourceQuestions>
         <question>
              <setup>A raster graphics editor</setup>
              <answerChoice1>The Gimp</answerChoice1>
              <answerChoice2>The Chimp</answerChoice2>
              <answerChoice3>The Pimp</answerChoice3>
              <answerChoice4>The Blimp</answerChoice4>
              <correctAnswer>The Gimp</correctAnswer>
         </question>
         <question>
              <setup>test question 2</setup>
              <answerChoice1>question2 answer1</answerChoice1>
              <answerChoice2>question2 answer2</answerChoice2>
              <answerChoice3>question2 answer3</answerChoice3>
              <answerChoice4>question2 answer4</answerChoice4>
              <correctAnswer>question2 answer1</correctAnswer>
         </question>
    </OpenSourceQuestions>What i want to do is only spit out the xml for the first question, i.e. "A raster graphics editor" and its answers
    Here is my java code for reading in and arsing the file:
    void readXML(){
                try {
                     File fXmlFile = new File("MyXMLFile.xml");
                     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                     Document doc = dBuilder.parse(fXmlFile);
                     doc.getDocumentElement().normalize();
                     System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
                     NodeList nList = doc.getElementsByTagName("question");
                     System.out.println("-----------------------");
                     for (int temp = 0; temp < nList.getLength(); temp++) {
                       Node nNode = nList.item(temp);
                       if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                         Element eElement = (Element) nNode;
                         System.out.println("Question : "  + getTagValue("setup",eElement));
                         System.out.println("Answer1 : "  + getTagValue("answerChoice1",eElement));
                         System.out.println("Answer2 : "  + getTagValue("answerChoice2",eElement));
                         System.out.println("Answer3 : "  + getTagValue("answerChoice3",eElement));
                         System.out.println("Answer4 : "  + getTagValue("answerChoice4",eElement));
                } catch (Exception e) {
                  e.printStackTrace();
               private static String getTagValue(String sTag, Element eElement)
                     NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
                     Node nValue = (Node) nlList.item(0);
                     return nValue.getNodeValue();
               }

    IN the time since i posted i have solved my own query!

  • How to extract data from xml file and store that data inti data base table

    Hii All
    I have one table that table contains one column that column contain an XML file
    I want to extract data from that XML file and want to store that extracted data into an other table.
    That xml file has different different values
    I want to store that values into table in diff diff columns

    Hi,
    I am also facing the same problem.I have a .xml file and i need to import the data into the custom table in oracle database.
    Can you please let me know if you know the solution how to do it in oracle apps.
    Thanks,

  • Reading from XML file and updating the table ????

    Hi
    I have package which reads the hier.XML file and does Update inserts into the 5 tables
    i have table called MAIN_tbl with the column cur_date.
    The package kicks if this cur_date is one day less than the hier.XML file DT.
    Currently i m manually checking this date's to make sure the Main_tbl cur_date is n sync with
    hier.XML file DT.
    for example :- hier.xml file DT is "20091020" then main_table cur_date should be 10/19/2009
    in order to kicks of the pakage.
    what i m looking to do ??
    compare the hier.xml DT with the main_table cur_date,
    if cur_date is -1(Preivous day) of hier.xml DT then run hier_pkg(Package)
    if not then update main_table cur_date to -1(previous day) of the hier.xml DATE
    Then later write the above logic to update the main_table in a procedure, and
    then call the package from the procedure.
    below are the top few lines of the hier.XML file which is relevant to the one which we are trying to do
    <?xml version = '1.0'?>
    <HIER_POSTING num ="111" HIER_TYP="CD" DT="20091020" Global="Y">
    FYI : The hier.XML file is located in UNIX space.
    How do i accomplish this. any idea ????
    Thank you so much in advance. For giving a thought on this problem!!!

    Any thought on this guys ???
    Thanks!!

  • Reading an XML file and write the contents to another xml file in java

    Hi,
    I am new to xml parsing.My requirement is that I am getting a message (xml) using ibm MQ in the ByteArrayInputStream format.I have to read this xml message and write to another file.
    I am creating a POC for this.
    First I used simple reading and writing concept but the output is "java.io.FileInputStream@3e25a5 "
    Sample xml file
    - <Client>
    <ClientId>1234</ClientId>
    <ClientName>STechnology</ClientName>
    <DTU_ID>567</DTU_ID>
    <ClientStatus>ACTIVE</ClientStatus>
    - <LEAccount>
    <ClientLE>678989</ClientLE>
    <LEId>56743</LEId>
    - <Account>
    <AccountNumber>9876543678</AccountNumber>
    </Account>
    </LEAccount>
    - <Service>
    <Cindicator>Y2Y</Cindicator>
    <PrefCode>980</PrefCode>
    <BSCode>876</BSCode>
    <MandatoryContent>MSP</MandatoryContent>
    </Service>
    </Client>
    code:
    import java.io.ByteArrayInputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class ByteArrayInputStreamToXml {
         public static void main(String srg[]) throws IOException{
              InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
              byte currentXMLBytes[] = inputStream.toString().getBytes();
              ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
              OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
              int read=0;
              byte[] bytes = new byte[1024];
              while((read = byteArrayInputStream.read(bytes))!= -1){
              out.write(bytes, 0, read);
              out.write( '\n' );
              inputStream.close();
              out.flush();
              out.close();
              System.out.println("New file created!");
    Please suggest me how can I use DOM/SAX parser ,I can see several code on net for reading xml file using SAX/DOM parser but writing an xml file after reading it using ByteArrayInputStream I am not getting .A help through some example Link will also be helpful for me.
    Thanks
    Sumit
    Edited by: user8687839 on Apr 30, 2012 2:37 AM
    Edited by: user8687839 on Apr 30, 2012 2:43 AM

    Thanks I got the result.
    package com.sumit.collections;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class ByteArrayInputStreamToXml {
         public static void main(String srg[]) throws IOException{
              InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
              ByteArrayOutputStream buffer = new ByteArrayOutputStream();
              int nRead; byte[] data = new byte[1024];
              while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
              buffer.write(data, 0, nRead); } buffer.flush();
              byte currentXMLBytes[]= buffer.toByteArray();
              /* byte currentXMLBytes[] = inputStream.toString().getBytes();*/
              ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
              OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
              int read=0;
              byte[] bytes = new byte[1024];
              while((read = byteArrayInputStream.read(bytes))!= -1){
              out.write(bytes, 0, read);
              out.write( '\n' );
              inputStream.close();
              out.flush();
              out.close();
              System.out.println("New file created!");
    }

  • Read of XML file and post to IDOC

    Hi
    I'm working on a <b>WAS620</b> and need to read an XML file from a customer, extract the fields needed and post these via IDOC ORDERS01. My problem is HOW to read the XML file? Can anyone give me the steps involved/links to examples etc - I have not processed XML files via ABAP before.
    The file is posted to a shared folder and the ABAP I am about to develop will pick up this file.
    The file is <b>NOT</b> in IDOC/XML format but the customers own format
    Hope someone can help me asap.
    Thanks all in advance
    /Bo

    Hi,
    I would like to extend this question for <b>WAS620</b> and <b>reading</b> a <b>proprietary customer specific XML</b> file/data that is <b>send via HTTP to SAP WAS</b>.
    <b>Q1</b>: What is the best way to read this HTTP sent XML data (as it is, without transformations) into ABAP?
    <b>Q2</b>: What is the appropriate handler to use in the ICF object?
    Thanks all in advance

  • Read  an XML file and send it to client

    Hi,
    I'm introducing to servlet development and I'm trying to do some AJAX calls. The client side is implemented, but I have some troubles on the server side. I want to open an XML file and send it to the client. How can I do that? Any special header?
    I have implemented this test in PHP, so you can imagine what I would like to do:
    if ($type == "xml"){
         $xml = "";
         $file = fopen ("file.xml", "r");
         while (!feof ($file)){
              $xml .= fgets ($file, 4096);
         fclose ($file);
         header ("Content-type: text/xml; charset=ISO-8859-1");
         echo $xml;
    }The XML file is:
    <?xml version='1.0' encoding='ISO-8859-1'?>
    <users>
         <user>
              <name>Pepe</name>
              <age>18</age>
         </user>
         <user>
              <name>María</name>
              <age>21</age>
         </user>
    </users>Thanks.

    Not very useful:(.
    This is my code:
    PrintWriter out = null;
            try{
                   String type = request.getParameter ("type");
                   if (type.equals ("xml")){
                        response.setContentType ("text/xml; charset=ISO-8859-1");
                        out = response.getWriter ();
                        String xml =
                             "<?xml version='1.0' encoding='ISO-8859-1'?>" +
                             "<users>" +
                                  "<user>" +
                                       "<name>Pepe</name>" +
                                       "<age>18</age>" +
                                  "</user>" +
                                  "<user>" +
                                       "<name>María</name>" +
                                       "<age>21</age>" +
                                  "</user>" +
                             "</users>";
                        out.println (xml);
            }finally{
                out.close ();
            }This code works. The servlet send back the xml and the client shows the content but, as you can see, i'm not reading the xml file. So my problem is on reading the xml file as a plain text. My code is this:
    response.setContentType ("text/xml; charset=ISO-8859-1");
                        out = response.getWriter ();
                        String xml = "";
                        FileReader fr = null;
                        BufferedReader br = null;
                        try{
                             fr = new FileReader (new File ("file.xml"));
                             br = new BufferedReader (fr);
                             String linea;
                             while ((linea = br.readLine ()) != null){
                                  xml += linea;
                                  //System.out.println (linea);
                             fr.close ();
                        }catch (Exception e){
                             e.printStackTrace ();
                        }But now I get an Exception File not found. The xml file is in the web directory (I'm using net beans 6.8). Where I have to put the file?
    Thanks.
    Edited by: GagleKas on Mar 15, 2010 6:39 AM

  • Reading a xml file and Extract content of xml tags

    Hi,
    I need a InDesign script to Extract content of xml tags by reading a local xml file. And stamping the content of xml on InDesign Text frame.
    My sample xml is as follows .
    <events type="array">
    <event> 
    <aktiv_jn>J</aktiv_jn> 
    <enetpulse_id>1712408</enetpulse_id>
    <event_id>65974</event_id>
    <hjemmehold>AZ Alkmaar</hjemmehold>
    <id>93</id>
    <kickoff>2014-08-17T12:30:00+01:00</kickoff>
    <land_id>140</land_id>
    <land_navn>Holland</land_navn>
    <liga_id>13684</liga_id>
    <liga_navn>Eredivisie</liga_navn>
    <livebetting_jn>J</livebetting_jn>
    <marked_id>2897740</marked_id>
    <marked_nummer>138</marked_nummer>
    <marked_tekst>AZ Alkmaar - Ajax</marked_tekst>
    <moderkamp_jn>J</moderkamp_jn>
    <ob_bet_type>MR</ob_bet_type>
    <odds_1>2.95</odds_1>
    <odds_2>2.25</odds_2>
    <odds_x>3.35</odds_x>
    <program_slut>2014-08-18T23:59:00+01:00</program_slut>
    <program_start>2014-08-15T00:00:00+01:00</program_start>
    <resultat>2</resultat>
    <spilstop_dato_tid>2014-08-17T12:30:00+01:00</spilstop_dato_tid>
    <sport_id>21</sport_id>
    <sport_navn>Fodbold</sport_navn>
    <taerskel nil="true"/>
    <udehold>Ajax</udehold>
    <udfald_1_id>9661951</udfald_1_id>
    <udfald_2_id>9661953</udfald_2_id>
    <udfald_x_id>9661952</udfald_x_id>
    </event>
    </events>
    And on my Indesign Page upon execution of script: I need text like,
    land_navn:     Holland
    odds_1:     2.95
    odds_2:     2.25
    odds_x:     3.35

    Hi,
    Try:

  • Reading the XML file and displaying teh string with teh desired output

    Hi Gurus,
    I have an xml file as below.
    catalog>
    <book>
    <id>101</id>
    <genre>Computer</genre>
    <author>Jim Cortez</author>
    <title>XML for dummies</title>
    <price>44.95</price>
    <description>An in-depth look at creating mashed potatoes
    with XML.</description>
    </book>
    <book>
    <id>102</id>
    <author>George Bush</author>
    <title>I'm the decider</title>
    <genre>Fantasy</genre>
    <price>0.95</price>
    <description>I like milk and cookies.</description>
    </book>
    </catalog>
    I would like to display the Output as
    [<catalog>:1]
    [<book>:1]
    [<id>:1]
    [101:3]
    [</id>:2]
    [<genre>:1]
    [Computer:3]
    [</genre>:2]
    [<author>:1]
    [Jim Cortez:3]
    [</author>:2]
    [<title>:1]
    [XML for dummies:3]
    ............ etc., etc.,,
    here is the code template.......
    import java.io.*;
    class TagScanner implements TokenStream {
    public static final int BEGIN_TAG_TYPE = 1;
    public static final int END_TAG_TYPE = 2;
    public static final int TEXT_TYPE = 3;
    protected Reader reader = null;
    /** Lookahead char */
    protected char c;
    /** Text of currently matched token */
    protected StringBuffer text = new StringBuffer(100);
    public TagScanner(Reader reader) throws IOException {
    this.reader = reader;
    nextChar();
    protected void nextChar() throws IOException {
    c = (char)reader.read();
    public Token nextToken() throws IOException {
         if ( start of a tag ) {
         // scarf until end of tag
         // type is either BEGIN_TAG_TYPE or END_TAG_TYPE
         if ( end of file ) {
         type = Token.EOF_TYPE;
         text = "end-of-file";
         else {
         // scarf until start of a tag
         type = TEXT_TYPE;
         if ( just whitespace ) {
         // ignore and get another token
    return new Token(type, text.toString());
    Can someone please provide me the logic for the code please........... here is the complete link of the excersie http://www.antlr.org/wiki/display/CS652/Lexer+for+XML
    Many Thanks
    -M

    Can someone please provide me the logic for the code please..........The logic is pretty well spelled out for you in the description of the assignment and the outline for the code you provided. If you mean
    Can someone please do my homework for me....The answer to that is usually yes, someone can do your homework for you, but no, they usually won't actually do it for you.
    However, if you are really stuck on what to do, you should consider:
            if ( start of a tag ) {How would you know that you are at the start of a tag? Once you can answer that, the rest sort of works itself out as long as
                // scarf until end of tagyou realize what it means to 'scarf' and how to determine when an end-of-tag is reached (hint, very similar as to how to determine if you are at the start-of-tag).

  • Reading the XML file and displaying the string with the desired output

    Hi Gurus,
    I have an xml file as below.
    catalog>
    <book>
    <id>101</id>
    <genre>Computer</genre>
    <author>Jim Cortez</author>
    <title>XML for dummies</title>
    <price>44.95</price>
    <description>An in-depth look at creating mashed potatoes
    with XML.</description>
    </book>
    <book>
    <id>102</id>
    <author>George Bush</author>
    <title>I'm the decider</title>
    <genre>Fantasy</genre>
    <price>0.95</price>
    <description>I like milk and cookies.</description>
    </book>
    </catalog>
    I would like to display the Output as
    [<catalog>:1]
    [<book>:1]
    [<id>:1]
    [101:3]
    [</id>:2]
    [<genre>:1]
    [Computer:3]
    [</genre>:2]
    [<author>:1]
    [Jim Cortez:3]
    [</author>:2]
    [<title>:1]
    [XML for dummies:3]
    ............ etc., etc.,,
    here is the code template.......
    import java.io.*;
    class TagScanner implements TokenStream {
    public static final int BEGIN_TAG_TYPE = 1;
    public static final int END_TAG_TYPE = 2;
    public static final int TEXT_TYPE = 3;
    protected Reader reader = null;
    /** Lookahead char */
    protected char c;
    /** Text of currently matched token */
    protected StringBuffer text = new StringBuffer(100);
    public TagScanner(Reader reader) throws IOException {
    this.reader = reader;
    nextChar();
    protected void nextChar() throws IOException {
    c = (char)reader.read();
    public Token nextToken() throws IOException {
    if ( start of a tag ) {
    // scarf until end of tag
    // type is either BEGIN_TAG_TYPE or END_TAG_TYPE
    if ( end of file ) {
    type = Token.EOF_TYPE;
    text = "end-of-file";
    else {
    // scarf until start of a tag
    type = TEXT_TYPE;
    if ( just whitespace ) {
    // ignore and get another token
    return new Token(type, text.toString());
    Can someone please provide me the logic for the code please........... here is the complete link of the excersie
    http://www.antlr.org/wiki/display/CS652/Lexer+for+XML
    Many Thanks
    -M

    Can someone please provide me the logic for the code please..........The logic is pretty well spelled out for you in the description of the assignment and the outline for the code you provided. If you mean
    Can someone please do my homework for me....The answer to that is usually yes, someone can do your homework for you, but no, they usually won't actually do it for you.
    However, if you are really stuck on what to do, you should consider:
            if ( start of a tag ) {How would you know that you are at the start of a tag? Once you can answer that, the rest sort of works itself out as long as
                // scarf until end of tagyou realize what it means to 'scarf' and how to determine when an end-of-tag is reached (hint, very similar as to how to determine if you are at the start-of-tag).

Maybe you are looking for

  • How to Sort JTable data using Multiple fields (Date, time and string)

    I have to fill the JTable data with some date, time and string values. for example my table data looks like this: "1998/12/14","15:14:38","Unicorn1","row1" "1998/12/14","15:14:39","Unicorn2","row2" "1998/12/14","15:14:40","Unicorn4","row3" "1998/12/1

  • Primary Cost Element Report - Cost Center wise Totals

    Dear Seniors, Requirement is to have a report which gives Cost Center wise Totals (Net posted amount) for Primary cost elements with the following fields -- Company Code G/L account Business Area Cost Center Accounting Period Fiscal Year Net Posted A

  • PO Output type- Purchase Grp wise

    Dear All, Can we maintain PO Output type(NEU) Purchase group wise ? What are the possibilities we have. Regds, CB

  • Delivery quantity is greater than schedule line confirmation quantity (sales order)

    I am creating a sales order with 30 Mt. I confirmed 10 Mt (partial confirmation and based credit block) in schedule line Now I am going to create the delivery system automatic taking 10 Mt but when I am going to change the delivery means when I incre

  • "Hide" a preSign event for Reader version 8

    Hi all, I'm using the preSign event for my form, and for some different reasons those forms will be open with Adobe Reader 8 or 9. As the preSign is not compatible with the version 8, is it possible to "deactivate" the presign event if the user has t