Problems by getting info out of XML file with a HTTP request

Hi,
I have a litte question. I'm working on an application that works together with google maps. In my java code, I get general information about address out of one database table, and I want to add some geographic information like coordinates that I want to retrieve from Google Maps through HTTP:
Right now my code is like:
while (resultSet.next())
                         title = resultSet.getString("title").replaceAll("'","''").toUpperCase();
                         author = resultSet.getString("author").replaceAll("'","''").toUpperCase();
                         location = resultSet.getString("location").replaceAll("'","''").toUpperCase();
                         straatnaam = resultSet.getString("straatnaam").replaceAll("'","''").toUpperCase();
                         nummer = resultSet.getString("nummer");
                         landcode = resultSet.getString("landcode").replaceAll("'","''").toUpperCase();
                         address = straatnaam + " " + nummer + " , " + location + " " + landcode;
                         url = "http://maps.google.com/maps/geo?q=" + address + "&output=xml&key=+key+";
                         String query = "INSERT INTO data2 VALUES ('" + i + "','" + title + "','" + author + "','" + resultSet.getString("date1") + "','" + resultSet.getString("date2") + "','" + location + "','" + resultSet.getString("postcode") + "','" + straatnaam + "','" + resultSet.getString("nummer") + "','" + landcode + "','+something like url.getCoordX+','something like url.getCoordY')";
                         success = sql2.executeUpdate(query);
                         i++;
Now I don't know how I can handle that. Is it possible to do an HTTP request in Java without using Java Script of servlets? I just want to get the X and Y coordinates out of the XML file.
The XML file will be something like:
<kml xmlns="http://earth.google.com/kml/2.0">
<Response>
<name>1600 amphitheatre mountain view ca</name>
<Status>
<code>200</code>
<request>geocode</request>
</Status>
<Placemark>
<address>
1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA
</address>
<AddressDetails Accuracy="8">
<Country>
<CountryNameCode>US</CountryNameCode>
<AdministrativeArea>
<AdministrativeAreaName>CA</AdministrativeAreaName>
<SubAdministrativeArea>
<SubAdministrativeAreaName>Santa Clara</SubAdministrativeAreaName>
<Locality>
<LocalityName>Mountain View</LocalityName>
<Thoroughfare>
<ThoroughfareName>1600 Amphitheatre Pkwy</ThoroughfareName>
</Thoroughfare>
<PostalCode>
<PostalCodeNumber>94043</PostalCodeNumber>
</PostalCode>
</Locality>
</SubAdministrativeArea>
</AdministrativeArea>
</Country>
</AddressDetails>
<Point>
<coordinates>-122.083739,37.423021,0</coordinates>
</Point>
</Placemark>
</Response>
</kml>
many greetings and thanks in advance
Mathias

Hi, sorry for being not so clear. My question was actually if it is possible to do a HTTP request in Java without using servlets or being in Java Script. Actually my question was more specific for Google maps, because it didn't seem to work. It was my mistake, and already solved, to forget to make the webservice-call "URL-encoded". Because of that, I always received a HTTP 400 error, and that's why I thought it wouldn't be possible.
But now I have another, perhaps for you guys stupid question. The result I get from the webservice URL is of the form:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.0">
<Response>
     <name>nieuwelaan 38, Hamme</name>
     <Status>
          <code>200</code>
          <request>geocode</request>
     </Status>
     <Placemark id="p1">
          <address>Nieuwelaan 38, 9220 Hamme, Hamme, Belgium</address>
          <AddressDetails Accuracy="8" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
          <Country>
               <CountryNameCode>BE</CountryNameCode>
               <AdministrativeArea>
                    <AdministrativeAreaName>Vlaams Gewest</AdministrativeAreaName>
                    <SubAdministrativeArea>
                         <SubAdministrativeAreaName>Oost-Vlaanderen</SubAdministrativeAreaName>
                         <Locality>
                              <LocalityName>Hamme</LocalityName>
                              <DependentLocality>
                                   <DependentLocalityName>Hamme</DependentLocalityName>
                                   <Thoroughfare>
                                        <ThoroughfareName>Nieuwelaan 38</ThoroughfareName>
                                   </Thoroughfare>
                                   <PostalCode>
                                        <PostalCodeNumber>9220</PostalCodeNumber>
                                  </PostalCode>
                             </DependentLocality>
                        </Locality>
                    </SubAdministrativeArea>
               </AdministrativeArea>
         </Country>
         </AddressDetails>
         <Point>
               <coordinates>4.126295,51.097724,0</coordinates>
         </Point>
     </Placemark>
</Response>
</kml> Now I want to get the value of the coordinates field.
This is my code:
address = URLEncoder.encode(address, "UTF-8");
urlString = "http://maps.google.com/maps/geo?q=" + address + "&output=xml&key=ABQIAAAA9fEXNK-q6vKpPU0JCmPPkxQjbVBpjtblJJYkDfbMo0e51afwehRmujfvBtJqx1Qehg6e6QgCRY8poA";
url = new URL(urlString);
XPath xPath = XPathFactory.newInstance().newXPath();
Document domDoc = processData(url);
path = "/kml/Response/Placemark/Point/coordinates";
coord = xPath.evaluate(path, domDoc);
System.out.println("coord : " + coord);Now, in the last line, by writing out the value of coord to my screen, I get the value "1", instead of "4.126295,51.097724,0" I would expect, anyone knows what I'm doing wrong?
greetings
Mathias

Similar Messages

  • How can i send xml file with a http servlet request

    Hi
    Please tell me how can I send a xml file into http servlet request.
    I have a servlet(action) java file.From this servlet I have generate a xml file. Now I need to send that xml file to another servlet with http servlet request object.
    Dave.

    When you say you have generated an XML file what do you mean?
    Is it a file stored on disk? Then pass the file path as a string to the servlet.
    Is it stored in memory as an object? The pass a reference to the object to the servlet.
    Or are you asking how to communicate between servlets?
    Look in the JavaDocs for the RequestDispatcher class. You can use this class to forward the request to another servlet. Data can be passes using the RequestDispatcher by storing it as attributes using the request getAttribute and setAttribute methods. Also described in the JavaDOcs.
    http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/RequestDispatcher.html

  • Getting info out of an excel file like a database

    Hi,
    The problem i have is that i have to get info out of an excel file like a database. So i have to be able to perform a kind of query, but to an excel file. Is this possible?
    lay-out excel file:
    number | request | chemical composition
    | | C | Mn | Si | ....
    125654 | |0.20%|0.10%|0.05%|.....
    i should have to be able to search on the number and read the differend % (C, Mn, Si). This % are used in a formula to calculate a value that is used for DAQ
    I can do this action with an acces DB, but not with excel. The problem is that they used excel for some years now (where i work) and changing the excel file to a DB would be a very long w
    ork.
    If someone could help i'd appreciate it
    thx

    I tried it like you said, but i get the error: -2147217865
    exception occured.
    [Microsoft][ODBC Excel Driver] The microsoft jet database engine could not find the object 'Sheet1'. Make sure the object exists...
    So he doesn't seem to recognize a datasheet as a table (if i may compare it like this) when i choose the microsoft Excel driver with the workbook as described in your answer.
    Any ideas?
    i putted some attachements, maybe they make it easier to understand
    Attachments:
    test_excel_query.vi ‏37 KB
    test_query_excel.xls ‏90 KB

  • I keep getting the message This XML file does not appear to have any style information axxociated with it. The document tree is shown below Is this a serious problem?

    My daughter and i use same computer she uses firefox and recently we have noticed on facebook apps we get the message This XML file does not appear to have any style information axxociated with it. The document tree is shown below

    Clear the cache and the cookies from sites that cause problems.
    * "Clear the Cache": Tools > Options > Advanced > Network > Offline Storage (Cache): "Clear Now"
    * "Remove the Cookies" from sites causing problems: Tools > Options > Privacy > Cookies: "Show Cookies"
    Start Firefox in [[Safe Mode]] to check if one of the add-ons is causing the problem (switch to the DEFAULT theme: Tools > Add-ons > Appearance/Themes).
    * Don't make any changes on the Safe mode start window.
    See:
    * [[Troubleshooting extensions and themes]]

  • Problems with reading XML files with ISO-8859-1 encoding

    Hi!
    I try to read a RSS file. The script below works with XML files with UTF-8 encoding but not ISO-8859-1. How to fix so it work with booth?
    Here's the code:
    import java.io.File;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import java.net.*;
    * @author gustav
    public class RSSDocument {
        /** Creates a new instance of RSSDocument */
        public RSSDocument(String inurl) {
            String url = new String(inurl);
            try{
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document doc = builder.parse(url);
                NodeList nodes = doc.getElementsByTagName("item");
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    NodeList title = element.getElementsByTagName("title");
                    Element line = (Element) title.item(0);
                    System.out.println("Title: " + getCharacterDataFromElement(line));
                    NodeList des = element.getElementsByTagName("description");
                    line = (Element) des.item(0);
                    System.out.println("Des: " + getCharacterDataFromElement(line));
            } catch (Exception e) {
                e.printStackTrace();
        public String getCharacterDataFromElement(Element e) {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
                CharacterData cd = (CharacterData) child;
                return cd.getData();
            return "?";
    }And here's the error message:
    org.xml.sax.SAXParseException: Teckenkonverteringsfel: "Malformed UTF-8 char -- is an XML encoding declaration missing?" (radnumret kan vara f�r l�gt).
        at org.apache.crimson.parser.InputEntity.fatal(InputEntity.java:1100)
        at org.apache.crimson.parser.InputEntity.fillbuf(InputEntity.java:1072)
        at org.apache.crimson.parser.InputEntity.isXmlDeclOrTextDeclPrefix(InputEntity.java:914)
        at org.apache.crimson.parser.Parser2.maybeXmlDecl(Parser2.java:1183)
        at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:653)
        at org.apache.crimson.parser.Parser2.parse(Parser2.java:337)
        at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:448)
        at org.apache.crimson.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:185)
        at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
        at getrss.RSSDocument.<init>(RSSDocument.java:25)
        at getrss.Main.main(Main.java:25)

    I read files from the web, but there is a XML tag
    with the encoding attribute in the RSS file.If you are quite sure that you have an encoding attribute set to ISO-8859-1 then I expect that your RSS file has non-ISO-8859-1 character though I thought all bytes -128 to 127 were valid ISO-8859-1 characters!
    Many years ago I had a problem with an XML file with invalid characters. I wrote a simple filter (using FilterInputStream) that made sure that all the byes it processed were ASCII. My problem turned out to be characters with value zero which the Microsoft XML parser failed to process. It put the parser in an infinite loop!
    In the filter, as each byte is read you could write out the Hex value. That way you should be able to find the offending character(s).

  • How to get data out of XML?

    Hi,All.
    I am running SAX (JAXP1.01) in Applet to process XML file. My question is how to get data out of xml format according to the field name (@age,@rank etc)
    and write into string buffer seperated by comma.
    Should I use SAX or DOM? (file size is big)
    My xml as follow :
    <ROOT>
    <FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@team/relay}">
         <ObjectName>Field124</ObjectName>
         <FormattedValue>HUNTER</FormattedValue>
         <Value>HUNTER</Value>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@age}">
         <ObjectName>Field125</ObjectName>
         <FormattedValue> 19</FormattedValue>
         <Value> 19</Value>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@Rank}">
         <ObjectName>Field126</ObjectName>
         <FormattedValue>43</FormattedValue>
         <Value>43</Value>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{results.athrel_name}">
         <ObjectName>Field127</ObjectName>
         <FormattedValue>1-1 NORRIE</FormattedValue>
         <Value>1-1 NORRIE</Value>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@timefield2}">
         <ObjectName>Field128</ObjectName>
         <FormattedValue>1:54.75</FormattedValue>
         <Value>1:54.75</Value>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@timefield1course}">
         <ObjectName>Field129</ObjectName>
         <FormattedValue/>
         <Value/>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@timefield1std}">
         <ObjectName>Field130</ObjectName>
         <FormattedValue/>
         <Value/>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@timefield2course}">
         <ObjectName>Field131</ObjectName>
         <FormattedValue/>
         <Value/>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@timefield2std}">
         <ObjectName>Field132</ObjectName>
         <FormattedValue>QT</FormattedValue>
         <Value>QT</Value>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@points(left)}">
         <ObjectName>Field133</ObjectName>
         <FormattedValue/>
         <Value/>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@pointsdecimal}">
         <ObjectName>Field134</ObjectName>
         <FormattedValue/>
         <Value/>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:decimal" FieldName="{@points(right)}">
         <ObjectName>Field135</ObjectName>
         <FormattedValue>0</FormattedValue>
         <Value>0.00</Value>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@timefield1}">
         <ObjectName>Field136</ObjectName>
         <FormattedValue>1:55.98</FormattedValue>
         <Value>1:55.98</Value>
    </FormattedReportObject>
    <FormattedReportObject xsi:type="CTFormattedField" Type="xsd:string" FieldName="{@Rank}">
         <ObjectName>Field137</ObjectName>
         <FormattedValue>43</FormattedValue>
         <Value>43</Value>
    </FormattedReportObject>
    Repeat...
    </FormattedReportObject>
    </ROOT>
    ------------------------------------------------

    For big files use SAX: quicker and less memory usage.
    The xerces parser from Apache has some examples. Basically what you do is scan the XML, remembering what tag you are and once you find the right tag, read the contents.

  • How to eliminate empty tags in out put XML file in IDOC to File scenario

    Hi Experts,
    I am doing IDOC to File scenario.
    My Out put XML is in to FTP is as below
    <ITEMS>
        <item>
              <A>asdf<A>
              <B>GHIJ<B>
        </item>
        <item>
              <A>123<A>
              <B>G098<B>
        </item>
    </ITEMS>
    <ITEMS/>   -
    > Means no data
    <ITEMS/> -
    > Means no data
    <ITEMS>
        <item>
              <A>yyy<A>
              <B>zzz<B>
        </item>
        <item>
              <A>arrr<A>
              <B>Ghhh<B>
        </item>
    </ITEMS>
    Now I want to eliminate tages <ITEMS/> in out out put XML file ( PIwhich writes in File server).
    1) Is there any setting in communication channel to do this
    2) Is there any settings in Mapping proram to suppress parent tag if child tags are not available.
    I want output as below .
    <ITEMS>
        <item>
              <A>asdf<A>
              <B>GHIJ<B>
        </item>
        <item>
              <A>123<A>
              <B>G098<B>
        </item>
    </ITEMS>
    <ITEMS>
        <item>
              <A>yyy<A>
              <B>zzz<B>
        </item>
        <item>
              <A>arrr<A>
              <B>Ghhh<B>
        </item>
    </ITEMS>
    Thanks,
    Subbu

    items->mapwithdefalut(just empty in the value)-> euqals(check with empty constant)->not->createif->target node
    and make sure that as Ravi kanth said ...occurance is  min is 0 at target side
    Regards,
    Prasad.
    Edited by: PRASAD KONDA on May 21, 2009 1:50 PM

  • To run iTunes in 64-bit mooose the "Get Info" command in the File menu, and uncheck the "Open in 32-bit mode" checkbox in the iTunes Info window. but i doesn't have the tick thing plus i redownloaded it a

    To run iTunes in 64-bit mode, select the iTunes application in the Finder, choose the “Get Info” command in the File menu, and uncheck the “Open in 32-bit mode” checkbox in the iTunes Info window. but i doesn't have the tick thing plus i redownloaded it again and same message comes up

    Have you disclosed the "General" brick in the "Info" panel? Click the disclosure triangle to the left of "General":
    What is your iTunes version and MacOS X version?
    -- Léónie

  • How to display the Get info window for a file or folder

    Hello,
    How can I display the Get Info window for a file or folder using Applescript - instead of selecting it in the finder and using Command-I ?
    Thanks.
    lenpartico

    The item property that the Get Info was opened for is read only, so it doesn't look like you can just throw a file path at it. You could do something like telling the Finder to reveal the item, then keystroke the command, e.g.:
    <pre style="
    font-family: Monaco, 'Courier New', Courier, monospace;
    font-size: 10px;
    margin: 0px;
    padding: 5px;
    border: 1px solid #000000;
    width: 720px;
    color: #000000;
    background-color: #FFEE80;
    overflow: auto;"
    title="this text can be pasted into the Script Editor">
    tell application "Finder"
    reveal "Path:to:your:file"
    activate
    end tell
    tell application "System Events" to keystroke "i" using {command down}
    </pre>
    ... but this doesn't seem to be much different than the regular method. There are other methods to get various information, what are you wanting to do?
    Edit:
    Hmmm, I could have sworn (I do a lot of that these days) I tried Hiroto's method, but that does work. It still seems to be a roundabout way of doing something though.
    Message was edited by: red_menace

  • Jsp to get info out of servlet question

    Hey, I'm looking for a good site or tutorial with examples in how to get info out of a bean or servlet.
    for example I have a bean that querys a db for info. how do I print that info to a jsp page with out using the out.printWriter? I know I need to use the <jsp:useBean...
    but after I instantiate the bean how do I pull info off of it?

    The Sun Java Developer site has a tutorial for almost everything. Check out the J2EE tutorial at http://java.sun.com/j2ee/tutorial/1_3-fcs/index.html
    There is a section on using JavaBeans in JSP pages.

  • Sending XML Files with Certificate

    Hello everybody.
    I need develop an abap program for sending XML files with a certificate.
    How I can create this certificate?
    Somebody have an idea?
    Thank you everybody.
    Nelson

    Mikael,
    This sounds like one of the many quirks (perhaps bugs) related to how FrameMaker handles non-FM files in books. The current book model doesn't play well with XML files as chapters and this seems like yet another problem. Apparently, if an xref does not target another .fm file in the book, Frame assumes that the target file is not in the book and therefore will not be in the book PDF.
    There have been discussions here about this in the past. The solution that I use is to run an API client before publishing that converts all XML files to .fm files, and redirect all xrefs appropriately. Then, book features work as expected and PDFs come out as normal. This is not feasible, however, without the automation from the API client.
    There may be some who would say that the best approach is to use XML and books the way that the designers did account for... that is, the whole book becomes an XML document with entity references to the separate chapters. In my work, though, this model was not appropriate... rather, I needed a binary FM book to act like a book, except with XML files as chapters. So, I think I understand your situation.
    Is API programming or FrameScript an option for you? I think it may be the only way to get what you are looking for.
    Russ

  • Open XML file with user default browser and not the default editor.

    Hi,
    I'm writing a java program that appends numerous XML files together. The result is a NEW well formed XML document. Since i have an XSLT that performs several UI modifications on this xml file, the file extension must remain '.xml'. I need to open this xml file with the users default web browser. The problem is that:
    Runtime.getRuntime().exec(cmd);
    ....opens the xml file with the users default program for opening xml files which in my case is Oxygen. I want to force java to open this xml file with the users default web browser and nothing else.
    I guess i need the Windows command to perform the 'open with' feature but i have no idea what that command is or how to find it.
    Any ideas?
    Thanks,
    Varun Singh
    Edited by: Jagara00 on Jul 2, 2009 3:49 PM

    sabre150 wrote:
    Jagara00 wrote:
    Your right, but my question relates to the java issue and not the XSLT aspect of the problem. I am looking for a java solution for reasons i will no go into here. You have lost me.Me too.
    People do not often ask questions (or make challenges or observations) idly for the sake of 'theory'. It is most useful to explain to the best of your ability.
    As to
    "Since the Desktop class was only released with SE 6 I am forced to find another alternative. "
    There is an 'alternative'. You can import it into a 1.5 project. It was available as a free standing API before 1.6 - through JDIC. See [https://jdic.dev.java.net/documentation/Examples.html|https://jdic.dev.java.net/documentation/Examples.html] for more info.
    Edit 1:
    To a later reply
    "Do u .."
    ..want to spell incorrectly when you get frustrated?
    "..do not wish to.."
    ..get any help? That is the way you are heading.
    Edited by: AndrewThompson64 on Jul 3, 2009 9:27 AM

  • Create xml file with values from context

    Hi experts!
    I am trying to implement a WD application that will have some input fields, the value of those input fields will be used to create an xml file with a certain format and then sent to a certain application.
    Apart from this i want to read an xml file back from the application and then fill some other context nodes with values from the xml file.
    Is there any standard used code to do this??
    If not how can i do this???
    Thanx in advance!!!
    P.S. Points will be rewarded to all usefull answers.
    Edited by: Armin Reichert on Jun 30, 2008 6:12 PM
    Please stop this P.S. nonsense!

    Hi,
    you need to create three util class for that:-
    XMLHandler
    XMLParser
    XMLBuilder
    for example in my XML two tag item will be there e.g. Title and Organizer,and from ur WebDynpro view you need to pass value for the XML tag.
    And u need to call buildXML()function of builder class to generate XML, in that i have passed bean object to get the values of tags. you need to set the value in bean from the view ui context.
    Code for XMLBuilder:-
    Created on Apr 4, 2006
    Author-Anish
    This class is to created for having function for to build XML
    and to get EncodedXML
      and to get formated date
    package com.idb.events.util;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import com.idb.events.Event;
    public class XMLBuilder {
    This attribute represents the XML version
         private static final double VERSION_NUMBER = 1.0;
    This attribute represents the encoding
         private static final String ENCODING_TYPE = "UTF-16";
         /*Begin of Function to buildXML
    return: String
    input: Event
         public String buildXML(Event event) {
              StringBuffer xmlBuilder = new StringBuffer("<?xml version=\"");
              xmlBuilder.append(VERSION_NUMBER);
              xmlBuilder.append("\" encoding=\"");
              xmlBuilder.append(ENCODING_TYPE);
              xmlBuilder.append("\" ?>");
              xmlBuilder.append("<event>");
              xmlBuilder.append(getEncodedXML(event.getTitle(), "title"));
              xmlBuilder.append(getEncodedXML(event.getOrganizer(), "organizer"));
              xmlBuilder.append("</event>");
              return xmlBuilder.toString();
         /End of Function to buildXML/
         /*Begin of Function to get EncodedXML
    return: String
    input: String,String
         public String getEncodedXML(String xmlString, String tag) {
              StringBuffer begin = new StringBuffer("");
              if ((tag != null) || (!tag.equalsIgnoreCase("null"))) {
                   begin.append("<").append(tag).append(">");
                   begin.append("<![CDATA[");
                   begin.append(xmlString).append("]]>").append("</").append(
                        tag).append(
                        ">");
              return begin.toString();
         /End of Function to get EncodedXML/
         /*Begin of Function to get formated date
    return: String
    input: Date
         private final String formatDate(Date inputDateStr) {
              String date;
              try {
                   SimpleDateFormat simpleDateFormat =
                        new SimpleDateFormat("yyyy-MM-dd");
                   date = simpleDateFormat.format(inputDateStr);
              } catch (Exception e) {
                   return "";
              return date;
         /End of Function to get formated date/
    Code for XMLParser:-
    Created on Apr 12, 2006
    Author-Anish
    This is a parser class
    package com.idb.events.util;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import com.idb.events.Event;
    import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
    public class XMLParser {
    Enables namespace functionality in parser
         private final boolean isNameSpaceAware = true;
    Enables validation in parser
         private final boolean isValidating = true;
    The SAX parser used to parse the xml
         private SAXParser parser;
    The XML reader used by the SAX parser
         private XMLReader reader;
    This method creates the parser to parse the user details xml.
         private void createParser()
              throws SAXException, ParserConfigurationException {
              // Create a JAXP SAXParserFactory and configure it
              SAXParserFactory saxFactory = SAXParserFactory.newInstance();
              saxFactory.setNamespaceAware(isNameSpaceAware);
              saxFactory.setValidating(isValidating);
              // Create a JAXP SAXParser
              parser = saxFactory.newSAXParser();
              // Get the encapsulated SAX XMLReader
              reader = parser.getXMLReader();
              // Set the ErrorHandler
    This method is used to collect the user details.
         public Event getEvent(
              String newsXML,
              XMLHandler xmlHandler,
              IWDMessageManager mgr)
              throws SAXException, ParserConfigurationException, IOException {
              //create the parser, if not already done
              if (parser == null) {
                   this.createParser();
              //set the parser handler to extract the
              reader.setErrorHandler(xmlHandler);
              reader.setContentHandler(xmlHandler);
              InputSource source =
                   new InputSource(new ByteArrayInputStream(newsXML.getBytes()));
              reader.parse(source);
              //return the results of the parse           
              return xmlHandler.getEvent(mgr);
    Code for XMLHandler:-
    Created on Apr 12, 2006
    Author-Anish
    This is a parser class
    package com.idb.events.util;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import com.idb.events.Event;
    Created on Apr 12, 2006
    Author-Anish
    *This handler class is created to have constant value for variables and function for get events,
        character values for bean variable,
        parsing thr date ......etc
    package com.idb.events.util;
    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    import java.util.*;
    import com.idb.events.Event;
    import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
    public class XMLHandler extends DefaultHandler {
         private static final String TITLE = "title";
         private static final String ORGANIZER = "organizer";
         IWDMessageManager manager;
         private Event events;
         private String tagName;
         public void setManager(IWDMessageManager mgr) {
              manager = mgr;
    This function is created to get events
         public Event getEvent(IWDMessageManager mgr) {
              manager = mgr;
              return this.events;
    This function is created to get character for setting values through event's bean setter method
         public void characters(char[] charArray, int startVal, int length)
              throws SAXException {
              String tagValue = new String(charArray, startVal, length);
              if (TITLE.equals(this.tagName)) {
                   this.events.setTitle(tagValue);
              if (ORGANIZER.equals(this.tagName)) {
                   String orgName = tagValue;
                   try {
                        orgName = getOrgName(orgName);
                   } catch (Exception ex) {
                   this.events.setOrganizer(orgName);
    This function is created to parse boolean.
         private final boolean parseBoolean(String inputBooleanStr) {
              boolean b;
              if (inputBooleanStr.equals("true")) {
                   b = true;
              } else {
                   b = false;
              return b;
    This function is used to call the super constructor.
         public void endElement(String uri, String localName, String qName)
              throws SAXException {
              super.endElement(uri, localName, qName);
         /* (non-Javadoc)
    @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
    This function is used to call the super constructor.
         public void fatalError(SAXParseException e) throws SAXException {
              super.fatalError(e);
    This function is created to set the elements base on the tag name.
         public void startElement(
              String uri,
              String localName,
              String qName,
              Attributes attributes)
              throws SAXException {
              this.tagName = localName;
              if (ROOT.equals(tagName)) {
                   this.events = new Event();
         public static void main(String a[]) {
              String cntry = "Nigeria";
              XMLHandler xml = new XMLHandler();
              ArrayList engList = new ArrayList();
              engList = xml.getCountries();
              ArrayList arList = xml.getArabicCountries();
              int engIndex = engList.indexOf(cntry);
              System.out.println("engIndex  :: " + engIndex);
              String arCntryName = (String) arList.get(engIndex);
              System.out.println(
                   ">>>>>>>>>>>>>>>>>>>>" + xml.getArabicCountryName(cntry));
    Hope that may help you.
    If need any help , you are most welcome.
    Regards,
    Deepak

  • Combine several XML files with same structure

    Hello,
    I have several XML files with the same structure and I want to combine them and create a new XML file to be bale to compare that information easily. It does not look very difficult but as I am very new in this I am not bale to get it
    The structure of my actual files would be something simlar to:
    Root->...-> Name->Address, Telephone
    And what I would like to have si something like
    Root->.... ->Address-> Name 1,Name 2....
    Root -> ...->Telephone-> Name 1, Name 2....
    Does anyone know how to do this.
    Thanks

    You could write a XSL transformation file that does this and transform your input file via
         * Transform XML file with a style sheet.
         * <p><b>Example:</b><p>
    <table align="center" bgcolor="#E0E0E0" border=1 cellpadding="10" cellspacing="0"><tr><td><pre style="margin-top:0; margin-bottom:0">
    XMLTransformer t = new XMLTransformer();
    FileOutputStream fos = new FileOutputStream("C:/Project/result.html");
    String xmlFile = "C:/Project/source.xml";
    String styleSheet = "C:/Project/stylesheet.xsl";
    t.transform(xmlFile, styleSheet, fos);
    </pre></td></tr></table>
         * @param xmlfile The XML file to transform.
         * @param style Stylesheet to use for transformation.
         * @param outputStream OutputStream to write the transformed result to.
        public void transform(String xmlfile, String style, OutputStream outputStream) {
            DocumentBuilderFactory factory =  DocumentBuilderFactory.newInstance();
            //factory.setNamespaceAware(true);
            //factory.setValidating(true);
                //todo: use inputstreams instead of file names
                try {
                    File stylesheet = new File(style);
                    File datafile   = new File(xmlfile);
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    document = builder.parse(datafile);
                    // Use a Transformer for output
                TransformerFactory tFactory = TransformerFactory.newInstance();
                StreamSource stylesource = new StreamSource(stylesheet);
                Transformer transformer = tFactory.newTransformer(stylesource);
                DOMSource source = new DOMSource(document);
                StreamResult sr = new StreamResult(outputStream);
                transformer.transform(source, sr);
            } catch (TransformerConfigurationException tce) {
               // Error generated by the parser
               System.out.println ("\n**XMLTransformerr Factory error");
               System.out.println("   " + tce.getMessage() );
               // Use the contained exception, if any
               Throwable x = tce;
               if (tce.getException() != null) {
                   x = tce.getException();
               x.printStackTrace();
            } catch (TransformerException te) {
               // Error generated by the parser
               System.out.println ("\n** Transformation error");
               System.out.println("   " + te.getMessage() );
               // Use the contained exception, if any
               Throwable x = te;
               if (te.getException() != null) {
                   x = te.getException();
               x.printStackTrace();
             } catch (SAXException sxe) {
               // Error generated by this application
               // (or a parser-initialization error)
               Exception  x = sxe;
               if (sxe.getException() != null) {
                   x = sxe.getException();
               x.printStackTrace();
            } catch (ParserConfigurationException pce) {
                // Parser with specified options can't be built
                pce.printStackTrace();
            } catch (IOException ioe) {
               // I/O error
               ioe.printStackTrace();
        }//transform()

  • Loading XML file with missing elements dynamically through ODI

    Hi Guys ,
    I have the below xml file with two nodes Employee and Address. On a daily basis , sometimes the address element might not come in from the source xml file , but my interface has columns mapped to address elements, and hence it can fail due to the source element not being found in the file or data might not get loaded due to the 'and' condition in the sql query generated between the employee and address elements.  Is there a way where i can load the data dynamically where i can search in the file only for the elements (Employee) present and load data only for those elements dynamically?
    XML File:
    <?xml version="1.0" encoding="UTF-8" ?>
    <EMP>
    <Empsch>
    <Employee>
    <EmployeeID>12345</EmployeeID>
    <Initials>t</Initials>
    <LastName>john</LastName>
    <FirstName>doe</FirstName>
    </Employee>
    <Address>
    <WorkPhone>12345</WorkPhone>
    <WorkAddress>Test 234</WorkAddress>
    </Address>
    </Empsch>
    </EMP>
    Thanks ,
    Revanth Tambisetty

    I was able to resolve it by using left outer joins and referring the table structure from the XSD

Maybe you are looking for

  • HP PSC 2510 "All in One"  prints only

    When I installed 10.4, the other features of the all in one stopped working. For months I have been struggling with HP and have been told several times that new sortware was on the way. I recently installed their Image Zone software and it looks hope

  • Import XML Page through Unix Box

    Hi, I have created say xxx.xml page. Now I want to import this in database, so I am using import command from command prompt C:\jdev\jdevbin\jdev\bin. So to Import any page, I would require C:\jdev\jdevbin\jdev\bin and import utility on my local mach

  • About really bad experiance with Sales person and store manager

    Hi ,        Yesterday I have really bad day of my life. I visit verizon wireless store in shrewsbury, MA. I have some issue with my phone. I talk with sales representative about my phone issue. I explain him about my phone issue. She is not at all ta

  • Backup file too big using Disk Utility

    I need to back up my 160GB Mackintosh HD on my imac OSX 10.6.3 (Snow Leopard) using disk utility. After a short period of the imaging process I get a message saying 'file too big'. What can I do to resolve the problem? My external drive is 1TB with 5

  • Number of Photos Limit in iPhoto '09

    In iPhoto '06, there was a limit of 99 photos per slideshow. Is there a maximum number photos limit in the '09 version? Thanks,