How to select specific element from a XML document using JDBC?

Hi all,
I have a problem with selecting specific XML element in Oracle 11g release 1 from my java application. Data are stored in object-relational storage.
My file looks like:
<students>
<student id="1">
</student>
<student id="2">
</student>
<student id="3">
</student>
</students>
I need to select a specific <student> element. I've already tried few ways to achieve my goal but I failed.
SELECT extract(OBJECT_VALUE,'/students/student') FROM students - works fine, but this selects all <student> elements
SELECT extract(OBJECT_VALUE,'/students/student[1]') FROM students - which should select first <student> element works too but it causes exception when using JDBC driver returns:
java.sql.SQLException: Only LOB or String Storage is supported in Thin XMLType
     at oracle.xdb.XMLType.processThin(XMLType.java:2817)
     at oracle.xdb.XMLType.<init>(XMLType.java:1238)
     at oracle.xdb.XMLType.createXML(XMLType.java:698)
     at oracle.xdb.XMLType.createXML(XMLType.java:676)
     at cz.zcu.hruby.data.Select.getStudent(Select.java:45)
SELECT to_clob(extract(OBJECT_VALUE,'/students/student[1]')) FROM students - in this case I hoped that DB would convert result to CLOB but the element is quite large (definitely more than 4000 Bytes long which I find out from forum is limit). But this exception occurs:
java.sql.SQLException: ORA-19011: Character string buffer too small
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
     at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
     at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
     at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
     at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
     at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
     at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
     at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:953)
     at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:897)
     at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
     at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3387)
     at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3431)
     at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491)
     at cz.zcu.hruby.data.Select.getStudent(Select.java:40)
SELECT to_lob(extract(OBJECT_VALUE,'/students/student[1]')) FROM students - I hoped I can convert return value to a LOB value but that doesn't work for me either:
java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: expected -, got -
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:91)
     at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
     at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
     at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
     at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
     at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
     at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
     at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:791)
     at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:866)
     at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
     at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3387)
     at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3431)
     at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491)
     at cz.zcu.hruby.data.Select.getStudent(Select.java:40)
This behaviour raises two questions:
1) Why SELECT extract(OBJECT_VALUE,'/students/student') FROM students works but SELECT extract(OBJECT_VALUE,'/students/student[1]') FROM students does't ?
2) Is there any way how I can select specific element (element XPath /students/student[@id="some value"]) and convert it to String?
Thanks for your responses I would appreciate any suggestion
Honza

To be exact my <student> element is a bit complicated and looks like the one at the end of this post (sorry but it's in czech). And I need to select whole xml fragment (all opening and closing tags included) as it is shown. Maybe I used wrong solution and I should use CLOB storage. I discuss this issue here: Which solution for better perfomance?
Thanks anyway for your response. I would be very grateful if you have any further idea
<Student RodneCislo="8051015555">
               <Jmeno>Petra</Jmeno>
               <Prijmeni>Nováková</Prijmeni>
               <RodnePrijmeni>Novotná</RodnePrijmeni>
               <TitulPred>Bc.</TitulPred>
               <TitulZa>MBA.</TitulZa>
               <Adresa>
                    <Okres>3702</Okres>
                    <Obec>582786</Obec>
                    <CastObce>11908</CastObce>
                    <Ulice>Nova</Ulice>
                    <UliceCislo>4</UliceCislo>
                    <PSC>60000</PSC>
                    <Stat>203</Stat>
               </Adresa>
               <RodinnyStav>1</RodinnyStav>
               <StredniSkola>000559024</StredniSkola>
               <RokMatZkousky>2001</RokMatZkousky>
               <PPStudent DatumVerifikace="2006-08-04">
                    <SoubeznaStudia>1</SoubeznaStudia>
                    <SoubeznaStudiaMaxDelka>2.0</SoubeznaStudiaMaxDelka>
                    <CelkovaDobaStudia>1817</CelkovaDobaStudia>
               </PPStudent>
               <Studia>
                    <Studium VSFakulta="14330" StudijniProgram="B1801" ZapisDoStudia="2001-07-10">
                         <DelkaStudia>5.0</DelkaStudia>
                         <NovePrijaty>N</NovePrijaty>
                         <NavazujiciStudProgram>N</NavazujiciStudProgram>
               <PredchoziVzdelani>K</PredchoziVzdelani>
                         <PocetRocniku>5</PocetRocniku>
                         <AktualniRocnik>5</AktualniRocnik>
                         <UbytovaniVKoleji>3</UbytovaniVKoleji>
                         <UkonceniStudia Datum="2004-06-28" Zpusob="1" UdelenyTitul="Bc."/>
                         <StudiumEtapy>
                              <StudiumEtapa PlatnostOd="2001-07-10">
                                   <ObcanstviKvalifikator>1</ObcanstviKvalifikator>
                                   <ObcanstviStat>203</ObcanstviStat>
                                   <PobytVCR>A</PobytVCR>
                                   <JazykVyuky>cze</JazykVyuky>
                                   <StudijniObory>
                                        <Obor>1801R001</Obor>
                                        <Obor>1801R005</Obor>
                                   </StudijniObory>
                                   <AprobaceOboru>
                                        <Aprobace>01</Aprobace>
                                   </AprobaceOboru>
                                   <MistoVyuky>582786</MistoVyuky>
                                   <FormaStudia>P</FormaStudia>
                                   <Financovani>1</Financovani>
                                   <PreruseniStudia>S</PreruseniStudia>
                                   <PlatnostDo>2002-04-24</PlatnostDo>
                              </StudiumEtapa>
                              <StudiumEtapa PlatnostOd="2002-04-24">
                                   <ObcanstviKvalifikator>1</ObcanstviKvalifikator>
                                   <ObcanstviStat>203</ObcanstviStat>
                                   <PobytVCR>A</PobytVCR>
                                   <StudijniPobyt Forma="V" Program="51" Stat="056"/>
                                   <JazykVyuky>cze</JazykVyuky>
                                   <StudijniObory>
                                        <Obor>1801R001</Obor>
                                        <Obor>1801R005</Obor>
                                   </StudijniObory>
                                   <AprobaceOboru>
                                        <Aprobace>01</Aprobace>
                                   </AprobaceOboru>
                                   <MistoVyuky>582786</MistoVyuky>
                                   <FormaStudia>P</FormaStudia>
                                   <Financovani>1</Financovani>
                                   <PreruseniStudia>S</PreruseniStudia>
                                   <PlatnostDo>2002-09-01</PlatnostDo>
                              </StudiumEtapa>
                              <StudiumEtapa PlatnostOd="2002-09-01">
                                   <ObcanstviKvalifikator>1</ObcanstviKvalifikator>
                                   <ObcanstviStat>203</ObcanstviStat>
                                   <PobytVCR>A</PobytVCR>
                                   <JazykVyuky>cze</JazykVyuky>
                                   <StudijniObory>
                                        <Obor>1801R001</Obor>
                                        <Obor>1801R005</Obor>
                                   </StudijniObory>
                                   <AprobaceOboru>
                                        <Aprobace>01</Aprobace>
                                   </AprobaceOboru>
                                   <MistoVyuky>582786</MistoVyuky>
                                   <FormaStudia>P</FormaStudia>
                                   <Financovani>1</Financovani>
                                   <PreruseniStudia>S</PreruseniStudia>
                                   <PlatnostDo>2004-06-28</PlatnostDo>
                              </StudiumEtapa>
                         </StudiumEtapy>
                    </Studium>
                    <Studium VSFakulta="14330" StudijniProgram="N1802" ZapisDoStudia="2004-06-29">
                         <DelkaStudia>2.0</DelkaStudia>
                         <NovePrijaty>N</NovePrijaty>
                         <NavazujiciStudProgram>A</NavazujiciStudProgram>
                         <PredchoziVzdelani>R</PredchoziVzdelani>
                         <PocetRocniku>2</PocetRocniku>
                         <AktualniRocnik>1</AktualniRocnik>
                         <UbytovaniVKoleji>3</UbytovaniVKoleji>
                         <SocialniStipendia>
                              <SocialniStipendium NarokOd="2006-01-01">
<NarokDo>2006-10-30</NarokDo>
                              </SocialniStipendium>
                         </SocialniStipendia>
                         <UkonceniStudia Datum="" Zpusob="" UdelenyTitul=""/>
                         <PPStudium DatumVerifikace="2006-07-01">
                              <NovePrijatyVerif>N</NovePrijatyVerif>
                              <NovePrijatyKvalif>N</NovePrijatyKvalif>
                              <NavazujiciStudProgramVerif>A</NavazujiciStudProgramVerif>
                              <UkonceniStudiaVerif/>
                              <FinancovanoCR>A</FinancovanoCR>
                              <SberId>38</SberId>
                              <DobaStudia>
                                   <Cista>733</Cista>
                                   <VcetneNeuspechuDanehoTypu>733</VcetneNeuspechuDanehoTypu>
                                   <VcetneVsechNeuspechu>733</VcetneVsechNeuspechu>
                              </DobaStudia>
                              <PrestoupenoKamPosledni VSFakulta="14330" StudijniProgram="N1802" ZapisDoStudia="2004-06-29"/>
                              <UbytovaciStipendiumKod/>
                         </PPStudium>
                         <StudiumEtapy>
                              <StudiumEtapa PlatnostOd="2004-06-29">
                                   <ObcanstviKvalifikator>1</ObcanstviKvalifikator>
                                   <ObcanstviStat>203</ObcanstviStat>
                                   <PobytVCR>A</PobytVCR>
                                   <JazykVyuky>eng</JazykVyuky>
                                   <StudijniObory>
                                        <Obor>1801T001</Obor>
                                        <Obor>1801T025</Obor>
                                   </StudijniObory>
                                   <AprobaceOboru>
                                        <Aprobace>01</Aprobace>
                                   </AprobaceOboru>
                                   <MistoVyuky>582786</MistoVyuky>
                                   <FormaStudia>P</FormaStudia>
                                   <Financovani>1</Financovani>
                                   <PreruseniStudia>S</PreruseniStudia>
                                   <PlatnostDo/>
                                   <PPStudiumEtapa DatumVerifikace="2006-07-01">
                                        <FinancovaniVerif>1</FinancovaniVerif>
                                        <StudentRozpoctovy>O</StudentRozpoctovy>
                                        <SberId>38</SberId>
                                   </PPStudiumEtapa>
                              </StudiumEtapa>
                         </StudiumEtapy>
                    </Studium>
               </Studia>
          </Student>

Similar Messages

  • How do I retrieve elements in a xml document ?

    I would like to know how to retrieve elements from xml document ?
    I have created a document already, but how do I proceed from there ?
    Also, how do I access the values inside, the attributes and value ?
    Thank you.

    parse the xml file in node wise using compare criteria according to programmer choice u can able to retrieve the elements which u want promptly

  • How to check empty return from Get XML Document Data?

    If Get XML Document Data doesn't return a result, how do you test it? String.isEmpty() doesn't do the trick, it still throws the exception "java.lang.NullPointerException". I can't seem to be able to match that up to a cisco exception with a "On Exception Goto" step (which I put right before the XML Document Data step). Any clues anyone?

    Hi,
    Try this:
    variable=Get XML Document Data ()
    if(variable == null) then
         true
         false
    Gabriel.

  • How to ignore white space when parse xml document using xerces 2.4.0

    When I run the program with the xml given below the following error comes.
    Problem parsing the file.java.lang.NullPointerExceptionjava.lang.NullPointerExce
    ption
    at SchemaTest.main(SchemaTest.java:25)
    ============================================================
    My expectation is "RECEIPT". Pls send me the solution.
    import org.apache.xerces.parsers.DOMParser;
    import org.xml.sax.InputSource;
    import java.io.*;
    import org.xml.sax.ErrorHandler;
    import org.w3c.dom.*;
    public class SchemaTest {
    public static void main (String args[])
    try
    FileInputStream is = new FileInputStream(new File("C:\\ADL\\imsmanifest.xml"));
    InputSource in = new InputSource(is);
    DOMParser parser = new DOMParser();
    //parser.setFeature("http://xml.org/sax/features/validation", false);
    //parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "memory.xsd");
    //ErrorHandler errors = new ErrorHandler();
    //parser.setErrorHandler(errors);
    parser.parse(in);
    Document manifest = parser.getDocument();
    manifest.normalize();
    NodeList nl = manifest.getElementsByTagName("organization");
    System.out.println((((nl.item(0)).getChildNodes()).item(0)).getFirstChild().getNodeValue());
    catch (Exception e)
    System.out.print("Problem parsing the file."+e.toString());
    e.printStackTrace();
    <?xml version = '1.0'?>
    <organizations default="detail">
    <organization identifier="detail" isvisible="true">
    <title>RECEIPT</title>
    <item identifier="S100000" identifierref="R100000" isvisible="true">
    <title>Basic Module</title>
    <item identifier="S100001" identifierref="R100001" isvisible="true">
    <title>Objectives</title>
    <metadata/>
    </item>
    </item>
    <metadata/>
    </organization>
    </organizations>
    Is there a white space problem? How do I get rid from this problem.

    ok now i really wrote the whole code, a bit scrolling in the API is to hard?
                DocumentBuilderFactory dbf = new DocumentBuilderFactory();
                DocumentBuilder db = dbf.newDocumentBuilder();
                dbf.setNamespaceAware(true); //or set false
                Document d = db.parse(inputstream);

  • How to extract inline styles from a PDF document using Acrobat 9?

    I have a requirement for extracting all the contents along with the para level and character level styles from a PDF document in the form of XML. While doing so I'm getting lot of additional tags. In addition to that I'm not able to find the inline tags (character level tags) like bold, italics, superscripts etc and the page numbers. It would of great help if someone can throw light on this.
    Thanks.

    Moved to Acrobat Forum.

  • How can I transfer elements from an old document to a new one?

    Hi everybody,
    I'm quite new to InDesign and not really from this area, so I'm having a tough time learning how to use it. My first project is what I first thought would be simple for a start: a recipe book. So I started using different master pages for different categories - meat, fish, soups, etc. - and had my first problem when finding out it is not a good idea to have text frames in the master page, cause everytime I change something there and apply it to the others, it kind of messes up the existing pages and I get lots of duplicated frames. it got so messed up I figured the best thing would be to start a completely new document (I also found out I had the wrong margins and can use a normal A4 with bleed, and no bigger-sized page, as I'd done).
    Now I decided to start the whole thing over again, but I don't want to start from zero. So how can I:
    1) import my existing gradients?
    2) import my character styles and colors?
    3) import my texts? (I guess this is not very difficult, so I figure I can find out, but please tell me if there are any "tricks", cause I'm thinking of exporting my doc as txt and copy-pasting.)
    I'm sorry if this has already been posted in this forum or can be found in the help-section, but I swear I have looked for it and couldn't find it...
    Thanks already in advance!

    easiest are steps 1) and 2) :)
    make copy of your document, add new blank page on the end, select all pages without last - click delete icon :)
    next - delete all MasterPages
    next - redefine page size, margins, add MasterPages, etc.
    now - you can copy&paste your texts from old document :)
    robin
    www.adobescripts.com

  • How to read specific lines from a text file using external table or any other method?

    Hi,
    I have a text file with delimited data, I have to pick only odd number rows and load into a table...
    Ex:
    row1:  1,2,2,3,3,34,4,4,4,5,5,5,,,5  ( have to load only this row)
    row2:   8,9,878,78,657,575,7,5,,,7,7
    Hope this is enough..
    I am using Oracle 11.2.0 version...
    Thanks

    There are various ways to do this.  I would be inclined to use SQL*Loader.  That way you can load it from the client or the server and you can use a SQL*Loader sequence to preserve the row order in the text file.  I would load the whole row as a varray into a staging table, then use the TABLE and MOD functions to load the individual numbers from only the odd rows.  Please see the demonstration below.
    SCOTT@orcl12c> HOST TYPE text_file.csv
    1,2,2,3,3,34,4,4,4,5,5,5,,,5
    8,9,878,78,657,575,7,5,,,7,7
    101,201
    102,202
    SCOTT@orcl12c> HOST TYPE test.ctl
    LOAD DATA
    INFILE text_file.csv
    INTO TABLE staging
    FIELDS TERMINATED BY ','
    TRAILING NULLCOLS
    (whole_row VARRAY TERMINATED BY '/n' (x INTEGER EXTERNAL),
    rn SEQUENCE)
    SCOTT@orcl12c> CREATE TABLE staging
      2    (rn         NUMBER,
      3     whole_row  SYS.OdciNumberList)
      4  /
    Table created.
    SCOTT@orcl12c> HOST SQLLDR scott/tiger CONTROL=test.ctl LOG=test.log
    SQL*Loader: Release 12.1.0.1.0 - Production on Tue Aug 27 13:48:37 2013
    Copyright (c) 1982, 2013, Oracle and/or its affiliates.  All rights reserved.
    Path used:      Conventional
    Commit point reached - logical record count 4
    Table STAGING:
      4 Rows successfully loaded.
    Check the log file:
      test.log
    for more information about the load.
    SCOTT@orcl12c> CREATE TABLE a_table
      2    (rn       NUMBER,
      3     data  NUMBER)
      4  /
    Table created.
    SCOTT@orcl12c> INSERT INTO a_table (rn, data)
      2  SELECT s.rn,
      3         t.COLUMN_VALUE data
      4  FROM   staging s,
      5         TABLE (s.whole_row) t
      6  WHERE  MOD (rn, 2) != 0
      7  /
    17 rows created.
    SCOTT@orcl12c> SELECT * FROM a_table
      2  /
            RN       DATA
             1          1
             1          2
             1          2
             1          3
             1          3
             1         34
             1          4
             1          4
             1          4
             1          5
             1          5
             1          5
             1
             1
             1          5
             3        101
             3        201
    17 rows selected.

  • How to select an item from a dropdown menu using Enter key

    A website I frequently use opens with a dropdown menu. Using my former browser, I was able to select the an item from the dropdown list by hitting the first letter with my keyboard and then hitting Enter. (Think of entering an address and selecting TX from a dropdown menu of states. Often you can hit T twice to get to TX and then the Enter key will advance the cursor to the zip code field.) Since converting to Firefox, the Enter key no longer works to advance to the next screen...I now have to move the mouse to a "Go" button and click it after selecting the desired item from the downdown menu. It's a small thing, but constantly switching back and forth between mouse and keyboard is becoming annoying. Is there an option in Firefox to select items simply by highlighting them in the dropdown menu and hitting the Enter key, instead of having to use the mouse to click a "Go" button? Thanks

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    * Don't make any changes on the Safe mode start window.
    * https://support.mozilla.com/kb/Safe+Mode
    If it does work in Safe-mode then disable all extensions and then try to find which is causing it by enabling one at a time until the problem reappears.
    * Use "Disable all add-ons" on the [[Safe mode]] start window to disable all extensions.
    * Close and restart Firefox after each change via "File > Exit" (Mac: "Firefox > Quit"; Linux: "File > Quit")
    In Firefox 4 you can use one of these to start in <u>[[Safe mode]]</u>:
    * Help > Restart with Add-ons Disabled
    * Hold down the Shift key while double clicking the Firefox desktop shortcut (Windows)
    * https://support.mozilla.com/kb/Troubleshooting+extensions+and+themes

  • How to insert data into a table from an xml document

    using the XmlSql Utility, how do I insert data into a table from an xml document, using the sqlplus prompt.
    if i use the xmlgen.insertXML(....)
    requires a CLOB file, which i dont have, only the xml doc.
    Cant i insert directly from the doc to the table?
    the xmlgen examples I have seen first convert a table to a CLOB xmlString and then insert it into another table.
    Isnt there any other way?

    Your question is little perplexing.
    If you're using XML SQL Utility from
    the commandline, just use putXML.
    java OracleXML putXML
    null

  • Problem inserting value in CLOB column from an XML file using XSU

    Hi,
    When I try to insert CLOB value into Oracle9i database from an XML document using XSU, I get an exception as below.
    09:37:32,392 ERROR [STDERR] oracle.xml.sql.OracleXMLSQLException: 'java.sql.SQLException: ORA-03237: Initial Extent of specified size cannot be allocated
    ORA-06512: at "SYS.DBMS_LOB", line 395
    ORA-06512: at line 1
    ' encountered during processing ROW element 0. All prior XML row changes were rolled back. in the XML document.
    All Element tags in XML doc. is mapped to columns in the database. One of the table columns is CLOB. That is the one that gives the above exception. Here is the xml...
    ID - is autogenerated value.
    <?xml version="1.0" ?>
    <ROWSET>
    <ROW num="1">
    <ID></ID>
    <SEQ>
    GCATAGTTGTTATGAAGAAATGGAAGAAAAATGCACTCAAAGTTGGGCTGTCAGGCTGTCTGGGGCTGAATTCTGGTGTGACAGTGTGATGAAGCCATCTTTGAGCCTAAATTTGATAATGAGCCAGTCATGATCTGGTTGTGATTACTATAACAAGATTAAATCTGAATAAGAGAGCCACAACTTCTTTAAAGACAGATTGTCAAGTCATTACATGGAAGAGGGAGATTGCTCCTTTGTAAATCAGGCTGTCAGGCCAACTGAATGAAGGACGTCATTGTACAGTAACCTGATGAAGATCAGATCAACCGCTCACCTCGCCG
    </SEQ>
    </ROW>
    </ROWSET>
    Can anyone identify what's the problem.. and suggest a solution for this..?
    Thanks in advance..
    Viji

    Would you please specify the XDK verison and database version?

  • Inserting an element into an XML document

    I am simply looking insert a new element into an existing XML Document using JDOM. Here is my code so far:
    public class UserDocumentWriter {
         private SAXBuilder builder;
         private Document document;
         private File file = new File("/path/to/file/users.xml");
         private Element rootElement;
         public UserDocumentWriter() {
              builder = new SAXBuilder();
              try {
                   document = builder.build(file);
                   rootElement = document.getRootElement();
              } catch (IOException ioe) {
                   System.err.println("ERROR: Could not build the XML file.");
              } catch (JDOMException jde) {
                   System.err.println("ERROR: " + file.toString() + " is not well-formed.");
         public void addContact(String address, String contact) {
              List contactList = null;
              Element contactListElement;
              Element newContactElement = new Element("contact");
              newContactElement.setText(contact);
              List rootsChildren = rootElement.getChildren();
              Iterator iterator = rootsChildren.iterator();
              while (iterator.hasNext()) {
                   Element e = (Element) iterator.next();
                   if (e.getAttributeValue("address").equals(address)) {
                        contactListElement = e.getChild("contactlist");
                        contactListElement.addContent(newContactElement);
                        writeDocument(document);
         public void writeDocument(Document doc) {
              try {
                   XMLOutputter output = new XMLOutputter();
                   OutputStream out = new FileOutputStream(file);
                   output.output(doc, out);
              } catch (FileNotFoundException ntfe) {
                   System.err.println("ERROR: Output file not found.");
              } catch (IOException ioe) {
                   System.err.println("Could not output document changes.");
         }However, the problem is, the newly added element will always be appended to the end of the last line, resulting in the following:
    <contactlist>
                <contact>[email protected]</contact><contact>[email protected]</contact></contactlist>Is there anyway in which I can have the newly added element create it's own line for the purpose of tidy XML? Alternatively is there a better methodology to do the above entirely?

    Your question is not very clear.
    Do you want to know How to insert an element into an XML document?
    Answer: I can see you already know how to do it. You have added the element using addContent()
    or do you want to know How to display the XML in a tidy format?
    Answer: to view the XML in a properly formatted style you can you the Format class. A very basic way of viewing the XML would be:
       * Prints the Document to the specified file.
       * @param doc
       * @param filename
       * @param formatting
      public static void printDocToFile(Document doc, String strFileName,
          boolean formatting)
        XMLOutputter xmlOut = null;
        if (!formatting)
          xmlOut = new XMLOutputter();
        } else
          Format prettyFormat = Format.getPrettyFormat();
          prettyFormat.setOmitEncoding(false);
          prettyFormat.setOmitDeclaration(false);
          xmlOut = new XMLOutputter(prettyFormat);
        try
          if (doc != null)
            FileWriter writer = new java.io.FileWriter(strFileName, true);
            xmlOut.output(doc, writer);
            writer.flush();
            writer.close();
          } else
            System.out.println("Document is null.");
        catch (Exception ex)
          System.out.println(ex);
      }

  • Problem in digitally signing a particular element of an XML Document

    hi all!!
    I was trying to sign a particular element of an XML document using JSR105 (XML Digital Signatures) API.
    For which i used +#xpointer(id('idvalue'))+ and +#idvalue+ as the URI for the reference i create as below :
    Reference ref = fac.newReference("#xpointer(id('123')) ", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED,(TransformParameterSpec) null)), null, null);
    NOTE: Here 123 is the value of the attribute 'id' of the element i wish to sign in the input XML document.
    But when i try to digest and sign the the above created reference, i get the following exception (which is strange! atleast for me!)
    Exception in thread "main" javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: Can't resolve ID: '123' in ''
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.calculateDigestValue(ReferenceImpl.java:327)
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.sign(ReferenceImpl.java:237)
    at com.ibm.xml.crypto.dsig.dom.XMLSignatureImpl.sign(XMLSignatureImpl.java:158)
    at sent.Generate.main(Generate.java:103)
    Caused by: javax.xml.crypto.URIReferenceException: Can't resolve ID: '123' in ''
    at com.ibm.xml.crypto.dsig.dom.URIDereferencerImpl.dereference(URIDereferencerImpl.java:193)
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.calculateDigestValue(ReferenceImpl.java:285)
    +... 3 more+
    javax.xml.crypto.URIReferenceException: Can't resolve ID: '123' in ''
    at com.ibm.xml.crypto.dsig.dom.URIDereferencerImpl.dereference(URIDereferencerImpl.java:193)
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.calculateDigestValue(ReferenceImpl.java:285)
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.sign(ReferenceImpl.java:237)
    at com.ibm.xml.crypto.dsig.dom.XMLSignatureImpl.sign(XMLSignatureImpl.java:158)
    at sent.Generate.main(Generate.java:103)
    I've given the whole Java code i used to generate the signature and the XML i used below for you to get a clear picture of what i tried...
    Any suggestions are very much welcome..
    thanks..
    ragu
    Generate.java
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.security.InvalidAlgorithmParameterException;
    import java.security.KeyException;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import javax.xml.crypto.MarshalException;
    import javax.xml.crypto.dsig.CanonicalizationMethod;
    import javax.xml.crypto.dsig.DigestMethod;
    import javax.xml.crypto.dsig.Reference;
    import javax.xml.crypto.dsig.SignatureMethod;
    import javax.xml.crypto.dsig.SignedInfo;
    import javax.xml.crypto.dsig.Transform;
    import javax.xml.crypto.dsig.XMLSignature;
    import javax.xml.crypto.dsig.XMLSignatureException;
    import javax.xml.crypto.dsig.XMLSignatureFactory;
    import javax.xml.crypto.dsig.dom.DOMSignContext;
    import javax.xml.crypto.dsig.keyinfo.KeyInfo;
    import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
    import javax.xml.crypto.dsig.keyinfo.KeyValue;
    import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
    import javax.xml.crypto.dsig.spec.TransformParameterSpec;
    import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    public class Generate {
          * @param args
          * @throws NoSuchAlgorithmException
          * @throws InvalidAlgorithmParameterException
          * @throws KeyException
          * @throws ParserConfigurationException
          * @throws IOException
          * @throws SAXException
          * @throws FileNotFoundException
          * @throws XMLSignatureException
          * @throws MarshalException
          * @throws TransformerException
         public static void main(String[] args) throws NoSuchAlgorithmException,
                   InvalidAlgorithmParameterException, KeyException,
                   FileNotFoundException, SAXException, IOException,
                   ParserConfigurationException, MarshalException,
                   XMLSignatureException, TransformerException {
              java.security.Security
                        .addProvider(new com.ibm.xml.crypto.IBMXMLCryptoProvider());
              XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
                        new com.ibm.xml.crypto.IBMXMLCryptoProvider());
              //reference generation
              //its here where I point the URI to the element i want to digest
              Reference ref = fac.newReference("#xpointer(id('123'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED,(TransformParameterSpec) null)), null, null);
              //signedinfo element generation
              SignedInfo si = fac
                        .newSignedInfo(fac.newCanonicalizationMethod(
                                  CanonicalizationMethod.INCLUSIVE,
                                  (C14NMethodParameterSpec) null), fac
                                  .newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                                  Collections.singletonList(ref));
              KeyInfoFactory kif = fac.getKeyInfoFactory();
              //Create a DSA KeyPair
              KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
              kpg.initialize(512);
              KeyPair kp = kpg.generateKeyPair();
              KeyValue kv = kif.newKeyValue(kp.getPublic());
              // Create a KeyInfo and add the KeyValue to it
              KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
              // Instantiate the document to be signed
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setNamespaceAware(true);
              Document doc = dbf.newDocumentBuilder().parse(
                        new FileInputStream(new File("shippedPedigree.xml")));
              // Create a DOMSignContext and specify the DSA PrivateKey and
              // location of the resulting XMLSignature's parent element
              DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc
                        .getDocumentElement());
              //Create the XMLSignature (but don't sign it yet)
              XMLSignature signature = fac.newXMLSignature(si, ki);
              // Marshal, generate (and sign) the enveloped signature
              signature.sign(dsc);
              //writing the signed document back to the file
              OutputStream os;
              os = new FileOutputStream(new File("shippedpedigree.xml"));
              TransformerFactory tf = TransformerFactory.newInstance();
              Transformer trans = tf.newTransformer();
              trans.transform(new DOMSource(doc), new StreamResult(os));
    the "shippedPedigree.xml" i used to sign:
    <?xml version="1.0" encoding="UTF-8"?>
    <ped:pedigree xmlns:ped="urn:epcGlobal:Pedigree:xsd:1" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ped:shippedPedigree id="123">
    <ped:documentInfo>
    <ped:serialNumber>2233</ped:serialNumber>
    <ped:version>ped:version</ped:version>
    </ped:documentInfo>
    <ped:signatureInfo>
    <ped:signerInfo>
    <ped:name>Joe Doe</ped:name>
    <ped:title>Manager</ped:title>
    <ped:telephone>800-521-6010</ped:telephone>
    <ped:email>[email protected]</ped:email>
    <ped:url>www.kittinginc.com</ped:url>
    </ped:signerInfo>
    <ped:signatureDate>2001-12-31T12:00:00</ped:signatureDate>
    <ped:signatureMeaning>Certified</ped:signatureMeaning>
    </ped:signatureInfo>
    <ped:itemInfo>
         <ped:lot>123</ped:lot></ped:itemInfo>
    </ped:shippedPedigree></ped:pedigree>
    ------------------------------------------------------------------------

    Sabarisri N wrote:
    Hi All,
    my xml is like below.
    <ns1:abcd>
    <ns2:a>1</ns2:a>
    <ns2:b>2</ns2:b>
    </ns1:abcd>
    If i try retrieving the value of the root element of this xml document,
    Node myroot=doc.getDocumentElement();
    String result=myroot.getNodeName();
    My output is ns1:abcd .. i want only "abcd"...
    The parser is returning the correct rootNodeName i.e ns1:abcd. rootNodeName always goes with the given input and returns the root element as is.
    >
    My xml will not always have same namespaces.. from the incoming xml i should first check, for the namespaces..Please give me some idea.
    I guess.. I need some namespace evaluation to be set..
    Refer below link it'll give idea of identifying XML-NAMESPACE-PREFIX
    http://java.sun.com/developer/Books/xmljava/ch03.pdf
    http://download.oracle.com/javaee/1.4/tutorial/doc/JAXPSAX9.html
    Please help me in this regard.
    Thanks,
    Sabarisri. N

  • To run a report from command line, when using jdbc-odbc bridge

    Hi,
    How to run a report from command line, when using jdbc-odbc bridge?
    Usually with tns, we do by "rwrun module=<> userid=<user>/<passwd>@tns".
    with odbc, we do by "rwrun module=<> userid=<user>/<passwd>@odbc:DSN"
    Please specify, what is command line arguments for jdbc-odbc bridge driver?
    Environment : Oracle 9i Report Builder on WinNT
    Database : Sybase
    Regards,
    Ramanan

    Hello Ramanan,
    Report Builder : connect JDBC Query in Report Builder is to through Connection Dialog in JDBC Query Editor. User can use a Sign on parameter (can use, default : P_JDBCPDS or can create new) to connect to JDBC Data Source. Connection once made will be mentioned and will be reused through out Reports Builder.
    JDBC PDS allows user to connect one or more same or different kind of databases.
    While running report through runtime or Server, user can pass the sign on parameter(connection string) value, like any other user parameter.
    Syntax for connection string : <username>/<password>@databaseURL . The syntax of database part of connection string depend on the type of JDBC Driver used to connect to Data Source while designing the JDBC Query. databaseURL refer to the location of the database and its format depend on the JDBCPDS river selected in design time while creating the JDBC Query.
    rwrun eg :
    rwrun report=jdbc_odbc.rdf destype=file desname=output.html desformat=html P_JDBCPDS=scott/tiger@database
    Server eg :
    http://server.com:8888/servlet/RWServlet?server=MyReportServer+report=jdbc_odbc.rdf+destype=cache+desformat=html+P_JDBCPDS=scott/tiger@database
    http :
    Please see ORACLE_HOME/reports/conf/jdbcpds.conf for more information.
    With Regards
    Reports Team

  • How to get the values of all elements and sub elements from  following xml

    how to get the values of all elements and sub elements from following xml...
    <?xml version="1.0" encoding="UTF-8" ?>
    <List_AML_Finacle xmlns="http://3i-infotech.com/Cust_AML_Finacle.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://3i-infotech.com/Cust_AML_Finacle.xsd List_AML_Finacle.xsd">
    <TransactionID>TransactionID</TransactionID>
    <Match>
    <Src_Matched_Field>Src_Matched_Field</Src_Matched_Field>
    <List_Matched_Field>
    <FSFM_Matches>
    <NUMBER>NUMBER</NUMBER>
    <TERROR>TERROR</TERROR>
    <TU>TU</TU>
    <NAMEU>NAMEU</NAMEU>
    <DESCRIPT>DESCRIPT</DESCRIPT>
    <KODCR>KODCR</KODCR>
    <KODCN>KODCN</KODCN>
    <AMR>AMR</AMR>
    <ADDRESS>ADDRESS</ADDRESS>
    <SD>SD</SD>
    <RG>RG</RG>
    <ND>ND</ND>
    <VD>VD</VD>
    <GR>GR</GR>
    <YR>YR</YR>
    <MR>MR</MR>
    <CB_DATE>CB_DATE</CB_DATE>
    <CE_DATE>CE_DATE</CE_DATE>
    <DIRECTOR>DIRECTOR</DIRECTOR>
    <FOUNDER>FOUNDER</FOUNDER>
    <TERRTYPE>TERRTYPE</TERRTYPE>
    </FSFM_Matches>
    <OfacMatchDetails>
    <UID>UID</UID>
    <TITLE>TITLE</TITLE>
    <SDNTYPE>SDNTYPE</SDNTYPE>
    <REMARKS>REMARKS</REMARKS>
    <ID_UID>ID_UID</ID_UID>
    <IDTYPE>IDTYPE</IDTYPE>
    <IDNUMBER>IDNUMBER</IDNUMBER>
    <IDCOUNTRY>IDCOUNTRY</IDCOUNTRY>
    <ISSUEDATE>ISSUEDATE</ISSUEDATE>
    <EXPIRATIONDATE>EXPIRATIONDATE</EXPIRATIONDATE>
    <ADDRESS1>ADDRESS1</ADDRESS1>
    <ADDRESS2>ADDRESS2</ADDRESS2>
    <ADDRESS3>ADDRESS3</ADDRESS3>
    <CITY>CITY</CITY>
    <STATEORPROVINCE>STATEORPROVINCE</STATEORPROVINCE>
    <POSTALCODE>POSTALCODE</POSTALCODE>
    <COUNTRY>COUNTRY</COUNTRY>
    </OfacMatchDetails>
    </List_Matched_Field>
    </Match>
    </List_AML_Finacle>

    avoid multi post
    http://forum.java.sun.com/thread.jspa?threadID=5249519

  • How to Find Number of Given Element in a XML Document

    Hello Experts,
    I want to know the number of given element in a XML document. For example if we have an employees information as a XML document, can we have how many <phone> element in the XML document?
    Thanks in advance.
    Regards,
    JP

    Hello,
    Once you've answered all the above.
    If you can run xpath that supports functions against the xml, the expression:
    count(//phone)Otherwise, without leaving SQL:
    select count(*) from
    xmltable('//phone' passing
      -- Your XML goes here, could be a table column with type XMLTYPE.
      xmltype('<person><phone>123-456-7890</phone><phone>098-765-4321</phone></person>')
      columns phone varchar2(24 char) path '/phone'
    ;

Maybe you are looking for

  • Itunes not reading id3 tags

    For some reason, many of my songs that I imported using previous versions of itunes *specifically version 10.5* no longer are reading the ID3 tags correctly and now come up as unknown artists, unknown albums.  Is there anyway to fix this without doin

  • File Sharing MacBook with Mac Pro

    Have been researching how to set up the ability to see my Mac Pro's HD from my Mac Book. Have 4 HD's installed in Mac Pro and would like to access my photos on my Mac Pro from Mac Book. Have Photoshop CS3 Extended on both machines (need to de-activat

  • Photos too slow?

    I just recently updated all of my pictures to iPhoto, around 800 to be exact. My problem is that whenever I try to edit them, the picture will appear for a second and then it will say "loading photo" for the rest of the time and never actually load.

  • Scheduling Crystal report from BOE

    Hi, I have a Crystal report (based on ECC Function module) which doesn't retrieve data when I schedule it from BOE (infoview). I have Integration kit installed, and the crystal report works fine when i execute it manually. I think it is an issue with

  • Accounts Receivable:  Detail Aged Trial Balance

    Good Morning- Is there a detailed aged trial balance available in SAP or does it have to be customized.  I have reviewed all the available reports and none of them look like an aged trial balance. Please help.