Edit / Modify an XML Element using SAX.

My need is to read,update,delete elements from large (200-700MB) xml files. Because of large files I am using SAX parser. I am able to read the xml using events generated but the issue is how do I modify a perticular attribute or node value, add new node??
Apart from SAX is there any other better solution???
Any help wil be appreciated!!

if you meant "in a simple and quick way that will only change the desired value in the text file" i fear no, you can't

Similar Messages

  • Read any XML File Elements using SAX Parser in J2se

    Hi All
    I can able to parsed one structured XML file using SAX
    Sample code :
    // ===========================================================
         // SAX DocumentHandler methods
         // ===========================================================
         public void startDocument() throws SAXException {
              logger.info("Start of document");
         public void endDocument() throws SAXException {
              logger.info("End of document");
         public void startElement(String namespaceURI, String localName, // local
                   // name
                   String qualName, // qualified name
                   Attributes attrs) throws SAXException {
              elemName = new String(localName); // element name
              if (elemName.equals(""))
                   elemName = new String(qualName); // namespaceAware = false
              tagPosition = TAG_START;
              // Set the string for accumulating the text in a tag to empty
              elemChars = "";
              // If the element name is "row", create a new row instance
              // If the element is "indexxid", "ModelPrice", or "ModelSpread",
              // the value will be read in the method "characters" and stored.
              if (elemName.equals("row")) {
                   row = new IndexRow();
                   numRows++;
              // logger.info("Number of numRow:"+numRows);
         } // end method startElement
         public void endElement(String namespaceURI, String simpleName, // simple
                   // name
                   String qualName // qualified name
         ) throws SAXException {
              elemName = new String(simpleName);
              if (elemName.equals(""))
                   elemName = new String(qualName); // namespaceAware = false
              tagPosition = TAG_END;
              String indexId = new String();
              Double dblVal = new Double(0);
              // If element name is "row", put the current row in the map for row
              // instances
              if (elemName.equals("row")) {
                   if (numRows <= 5) { logger.info("Row is: " + row.toString()); }
                   //ABX
                   //indexRows.put(row.getIndexxId(), row);
                   if (family.equals("ABX.HE")){
                   indexRows.put(row.getIndexREDId(), row);
                   else {
                        //CDX ITRXX
                             indexRows.put(row.getIndexxId(), row);
              } else if (elemName.equals("IndexID")) {
                   row.setIndexxId(elemChars);
                   // Leave double value at default of zero if there are no chars
                   if (elemChars.trim().length() != 0) {
                        dblVal = new Double(elemChars);
                        row.setCompositeSpread(dblVal);
                        indexId = row.getIndexxId();
              } else if (elemName.equals("REDCode")) {
                   row.setRedCode(elemChars);
              else if (elemName.equals("Name")) {
                   row.setRowName(elemChars);
              } else if (elemName.equals("Series")) {
                   row.setSeries(elemChars);
              } else if (elemName.equals("Version")) {
                   row.setVersion(elemChars);
              } else if (elemName.equals("Term")) {
                   row.setTerm(elemChars);
              } else if (elemName.equals("Maturity")) {
                   row.setMaturity(elemChars);
              } else if (elemName.equals("OnTheRun")) {
                   row.setOnTheRun(elemChars);
              } else if (elemName.equals("Date")) {
                   row.setRowDate(elemChars);
              } else if (elemName.equals("Depth")) {
                   row.setDepth(elemChars);
              else if (elemName.equals("Heat")) {
                   // logger.info("Chars for element " + elemName + " are '" +
                   // elemChars + "'");
                   // Leave double value at default of zero if there are no chars
                   if (elemChars.trim().length() != 0) {
                        dblVal = new Double(elemChars);
                        row.setHeat(dblVal);
                        indexId = row.getIndexxId();
    //          ABX.HE
              else if (elemName.equals("IndexREDId")){
                   row.setIndexREDId(elemChars);
              else if (elemName.equals("Coupon")){
                   row.setCoupon(elemChars);
              if (elemName.equals("Ontherun")) {
                   row.setOnTheRun(elemChars);
         } // end method endElement
         public void characters(char buf[], int offset, int len) throws SAXException {
              // If at end of element, there will be no characters
              if (tagPosition == TAG_END) {
                   return;
              // The characteres method may be called more than once
              // for an element if the internal buffer fills up.
              // Append the characters until the end of the element.
              String strVal = new String(buf, offset, len);
              elemChars = elemChars + strVal;
         } // end method characters
    } // end class MarkItIndexLoader
    but the problem is i want to read (parse) any XML file means any Elemets would be change any time using SAX .In the above example
    else if (elemName.equals("Heat")) {
    else if (elemName.equals("IndexREDId")){
    } else if (elemName.equals("Maturity")) {
    like above I am doing hard code Elements names and reading the values so i don't want hard coding the elements names I want to read any element name and value dynamically.
    If i give any one below XML file i want to read the Elements and displaying to console without changing any code i want to read the XML document.
    EX:
    Student.XML: <root>..</StName>..</StAge>...</root>
    Employee.XML: <root>..</EmpName>..</EmpAge>...</root>
    CdCatalog.XML: <root>..</Cdtitle>...</CdNumber>...</root>
    I need one java program can ready any type of XML file elements and send to the Database table.
    Please any one done like this task please suggest some reference links or books or sample snippet which can help me to develop program in my requirement.
    Thanks in advance
    Regards
    satish

    You should ask in the Java forum.
    Regards
    Stefan

  • How can we get  tag of XML file using SAX

    Hi ,
    I'm parsing one SAX parser , I'have almost done this parsing. i have faced problem for one case, i'e how can we get tag from XML file using SAX parser?
    XML file is
    <DFProperties>
    <AccessType>
    <Get/>
    </AccessType> <Description>
    gdhhd
    </Description>
    <DFFormat>
    <chr/>
    </DFFormat>
    <Scope>
    <Permanent/>
    </Scope>
    <DFTitle>gsgd</DFTitle>
    <DFType>
    <MIME>text/plain</MIME>
    </DFType>
    </DFProperties>
    I want out like GET and Permanent... means this one tag which is present inside of another tag.
    Handler class like
    public void startElement(String namespaceURI, String localName,
                   String qName, Attributes atts) throws SAXException {
    if(_ACCESSTYPE.equals(localName)){
                   accessTypeElement=ACCESSTYPE;
    public void characters(char[] ch, int start, int length)
                   throws SAXException {
    if (_ACCESSTYPE.equals(_accessTypeElement)) {
                   String strValue = new String(ch, start, length);
                   System.out.println("Accestype-----------------------------> " + strValue);
                   //System.out.println(" " + strValue);
    public void endElement(String namespaceURI, String localName, String qName)
                   throws SAXException {
    if (_ACCESSTYPE.equals(localName)) {
                   _accessTypeElement = "";
    . please any body help me

    Hi ,
    I have one problem,Please help me.
    1. How can I'll identify where exactly my Node is ended,means how how can we find corresponding nodename? in partcular place
    <Node> .............starttag1
    <NodeName>Test</NodeName>
    <Node>................starttag2
    <nodeName>test1</NodeName>
    </Node>..................endtag2
    <Node>.....................starttag3
    <NodeName><NodeName>
    <Node> .........................starttag4
    <NodeName>test4</NodeName>
    </Node>.......enddtag4
    </Node>...........end tag3
    </Node>............endtag1
    my code is below
    private final String _NODENAME = "NodeName";
    private final String _NODE = "Node";
    private String _nodeElement = "";
         private String _NodeNameElement = "";
    public void startElement(String namespaceURI, String localName,
                   String qName, Attributes atts) throws SAXException {
    if (_NODENAME.equals(localName)) {
                   NodeNameElement = NODENAME;
    if(_NODE.equals(localName)){
         System.out.println("start");
         if (_NODENAME.equals(localName)) {
                   NodeNameElement = NODENAME;
    public void characters(char[] ch, int start, int length)
                   throws SAXException {
    if (_NODENAME.equals(_NodeNameElement)) {
                   String strValue = new String(ch, start, length);
                   String sttt=strValue;
                   System.out.println("NODENAME: ************* " + strValue);
    if(_NODE.equals(_nodeElement)){
                   if (_NODENAME.equals(_NodeNameElement)) {
                        String strValue = new String(ch, start, length);
                        String sttt=strValue;
                        System.out.println("nodevalue********** " + strValue);
    public void endElement(String namespaceURI, String localName, String qName)
                   throws SAXException {
    if (_NODENAME.equals(localName)) {
                   _NodeNameElement = "";
    if(_NODE.equals(localName)){
                   System.out.println("NODENAME: %%%%%%%%%");
    please help me. How can I figure node ending for particular nodename

  • How to modify the content of a xml element using java?

    Hi all,
    In my usecase I need to export some data from the database to the external file (Ms Word) using java.
    The data which I get from the database will be in the form of a xml file. In that xml file
    I got to modify the content of an attribute of a xml element in the java class. Kindly comeup with your help
    to achieve this.
    Thanks,
    Phanindra.
    Edited by: 887737 on Dec 5, 2011 5:52 AM

    Why don't you try Xerces2?Why don't you tell him to use the javax.xml APIs that are already built in? And that use Xerces2 under the hood? Instead of throwing out a suggestion that might lead to him adding another copy of Xerces into his application?
    @OP there are several techniques:
    - string replacement as suggested by jschell
    - XML parsing to a DOM and then use the DOM API
    - XSLT
    Which you should use depends on the complexity of your requirement.

  • How to parse a specific inner element using SAX

    I would like to parse the values of <data> and store them but only the <data> values whose parent element is <process-type>.
    My xml file looks something like:
    <process-type id="IASPT" module-id="IASPT" working-dir="/apps/ora10G5/iaspt/bin">
         <port id="ajp" range="7501-7600"/>
         <process-set id="IASPT" numprocs="1"/>
    </process-type>
    <category id="stop-parameters">
          <data id="java-options" value="-Djava.awt.headless=true"/>
    </category>
    <process-type id="claimservices" module-id="OC4J" status="enabled">
         <environment>
               <variable id="DOCUMENTUM" value="/apps/dctmdev"/>
         </environment>
         <module-data>
               <category id="start-parameters">
                     <data id="java-options" value="-server -Djava.security.policy=$ORACLE_HOME/j2ee/claimservices/config/java2.policy"/>
               </category>
         </module-data>
    </process-type>
    <process-type id="ASG" module-id="custom">
          <process-set id="ASG" numprocs="1">
             <module-data>
                <category id="start-parameters">
                   <data id="java-options" value="-Djava.security.policy=$ORACLE_HOME/j2ee/sharedservices/config/java2.policy"/>
                </category>
             </module-data>
          </process-set>
    </process-type>
    ......I would like to read the value(s) of data which is within process-type. In this case:
    <data id="java-options" value="-server -Djava.security.policy=$ORACLE_HOME/j2ee/claimservices/config/java2.policy"/>
    <data id="java-options" value="-Djava.security.policy=$ORACLE_HOME/j2ee/sharedservices/config/java2.policy"/>I can read the elements, attributes and their values using SAX. The problem however is that when I read the file, it reads in not only the line I am interested in but also any <data> element within the XML file which is not what I want. I tried editing my code but it doesn't seem to work.
    The start element in my code looks like this:
    public void startElement(String name, String localName,
                   String qName, Attributes attr) throws SAXException {
              String processTypeId = "";
              String processTypeData = "";
              if (localName.equalsIgnoreCase("process-type")){
                   if (attr.getLocalName(0).equals("id")){
                        processTypeId = attr.getValue(0);
                        System.out.println("process_type/id: " + processTypeId);
              if (localName.equalsIgnoreCase("data")){
                   if (attr.getLocalName(1).equals("value")){
                        processTypeData = attr.getValue(1);
                        System.out.println("data/id: " + processTypeData);
    } Considering I have more than one process-type and that the first attribute of <data>, id, is the same for both, I should somehow tell SAX:
    1) Find process-type element
    2) Read its id attribute
    3) Read <data> element and its attributes under process-type if any
    4) Store <data> and attributes of each process-type (into possibly a map in the form of {process-type id, data value} pair??)
    I would appreciate your help with this very much.

    I thought the same. The good thing is that the first one is the one I want. The bad thing is that the first one might not necessarily be positioned at the top.
    What I mean is when I read this part of the XML file
    <process-type id="home" module-id="OC4J" status="enabled">
         <module-data>
               <category id="start-parameters">
                       <data id="java-options" value="-server -Djava.security.policy=$ORACLE_HOME/j2ee/home/config/java2.policy"/>
               </category>
               <category id="stop-parameters">
                       <data id="java-options" value="-Djava.security.policy=$ORACLE_HOME/j2ee/home/config/java2.policy"/>
               </category>
         </module-data>
    </process-type>I am interested in the value attribute of the <data> under <category> whose id attribute is "start-parameters". The thing is that the "start-parameters" and the "stop-parameters" postions could be switched so I cannot rely on the fact that my code reads the first one successfully.
    I tried editing my code like shown below but no luck
    if (localName.equalsIgnoreCase("process-type")){
                   //Extracting process-type attribute id
                   if (attr.getLocalName(0).equals("id")){
                        processTypeId = attr.getValue(0);
                        System.out.println("\nprocess_type/id: " + processTypeId);
              if (localName.equalsIgnoreCase("category")){
                   //Extracting process-type attribute id
                   if (attr.getLocalName(0).equals("id")){
                        categoryId = attr.getValue(0);
                        if (categoryId.equals("start-parameters")){
                             //System.out.println("\ncategory/id: " + categoryId);     
                             categoryStartParameters = categoryId;
                             startOfCategoryId = true;
              if (localName.equalsIgnoreCase("data")){
                   if (endOfProcessType){
                        if (startOfCategoryId /*&& (categoryStartParameters.equals("start-parameters"))*/){
                             if (attr.getLocalName(1).equals("value")){
                                  processTypeData = attr.getValue(1);
                                  System.out.println("\ndata/id: " + processTypeData);
                                  endOfProcessType = false;
         public void endElement(String uri, String localName, String qName) throws SAXException {
              if( localName.equalsIgnoreCase("process-type") ) {
                  endOfProcessType = true;
    ......Isn't there a more straightforward way to reading all the elements under a particular element in SAX?
    Please assume that all the variables are defined and initialised.

  • How to make XML element used in RTF PRIVATE/PUBLIC ? I know how to hide columns in RTF, but dont know how to generate the xml in below way. Please help.

    Hi
    I am following below link to hide/show my columns dynamically. See "Column Formatting"
    http://docs.oracle.com/cd/E12844_01/doc/bip.1013/e12187.pdf
    As per doc, element can be made private/public.
    <items type="PUBLIC">
    <item>
      <name>Plasma TV</name>
      <quantity>10</quantity>
      <price>4000</price>
    </item>
    <item>
    And same can be used to hide the column using condition
    <?if@column:/items/@type="PUBLIC"?>
    MY QUESTION IS HOW TO DO THIS IN MY XML BELOW?
    Below is part of my XML code which I am using in Data Definition for RTF.
    <group name="GH3" source="QH3">
    <element name="COLUMN_HEAD3" value="COLUMN_NAME" />
    </group>
    <group name="GH4" source="QH4">
    <element name="COLUMN_HEAD4" value="COLUMN_NAME" />
    </group>
    I am getting output like this.
    <LIST_GH3>
    <GH3>
    <COLUMN_HEAD3>REBILL_TO_OTHER_BUSINESS_UNIT</COLUMN_HEAD3>
    </GH3>
    </LIST_GH3>
    <LIST_GH4>
    <GH4>
    <COLUMN_HEAD4>XYZ</COLUMN_HEAD4>
    </GH4>
    </LIST_GH4>
    In order to use logic as per oracle document I want output like this.
    <LIST_GH3 type="PUBLIC">
    <GH3>
    <COLUMN_HEAD3>REBILL_TO_OTHER_BUSINESS_UNIT</COLUMN_HEAD3>
    </GH3>
    </LIST_GH3>
    <LIST_GH4 type="PRIVATE">
    <GH4>
    <COLUMN_HEAD4>BLANK</COLUMN_HEAD4>
    </GH4>
    </LIST_GH4>
    What changes I need to make in my XML code to get the runtime output as above? Please help. Where do i need to make changes in the above xml? Group name? Element name?
    I am planning to use below condition in RTF template to hide the column,  but dont know how to set the type of column as PRIVATE/PUBLIC in the XML output used to populate data in the RTF at runtime.
    <?if@column:/BTSPIEXP/LIST_GH3/@type=”PUBLIC”?>COLUMN_HEAD3<?end if?>
    Regards,
    Swapnil K.

    Hi,
    Issue has been resolved. I used the value of the element to determine to display it or not.
    Regards,
    Swapnil K.

  • Buiding xml file using SAX parser of JAXP

    Please send me xml building using the sax parser.This is the urgent requirement ,iam not geeting how to solve this problem.so please anybody can help with one best example

    You don't build an XML file with a parser. A parser reads an XML file and converts it to some internal representation. Try reading this tutorial:
    http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/

  • SAX: How to create new XML file using SAX parser

    Hi,
    Please anybody help me to create a XML file using the Packages in the 5.0 pack of java. I have successfully created it reading the tag names and values from database using DOM but can i do this using SAX.
    I am successful to read XML using SAX, now i want to create new XML file for some tags and its values using SAX.
    How can i do this ?
    Sachin Kulkarni

    SAX is a parser, not a generator.Well,
    you can use it to create an XML file too. And it will take care of proper encoding, thus being much superior to a normal textwriter:
    See the following code snippet (out is a OutputStream):
    PrintWriter pw = new PrintWriter(out);
          StreamResult streamResult = new StreamResult(pw);
          SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
          //      SAX2.0 ContentHandler.
          TransformerHandler hd = tf.newTransformerHandler();
          Transformer serializer = hd.getTransformer();
          serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"pdfBookmarks.xsd");
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"http://schema.inplus.de/pdf/1.0");
          serializer.setOutputProperty(OutputKeys.METHOD,"xml");
          serializer.setOutputProperty(OutputKeys.INDENT, "yes");
          hd.setResult(streamResult);
          hd.startDocument();
          //Get a processing instruction
          hd.processingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"mystyle.xsl\"");
          AttributesImpl atts = new AttributesImpl();
          atts.addAttribute("", "", "someattribute", "CDATA", "test");
          atts.addAttribute("", "", "moreattributes", "CDATA", "test2");
           hd.startElement("", "", "MyTag", atts);
    String curTitle = "Something inside a tag";
              hd.characters(curTitle.toCharArray(), 0, curTitle.length());
        hd.endElement("", "", "MyTag");
          hd.endDocument();
    You are responsible for proper nesting. SAX takes care of encoding.
    Hth
    ;-) stw

  • How to iterate xml elements using PL/SQL

    Hello,
    Let's say I have the following xml:
    <A>
    <B name="b1">
    </B>
    <B name="b2">
    </B>
    </A>
    I would like to iterate over the B and sub-B elements using PL/SQL?
    Any help will be appreciated.

    Hi,
    You can use 'PL/SQL DOM API for XMLType (DBMS_XMLDOM)'
    to work with XML. You can check the example present at
    http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/appdev.920/a96620/xdb08pls.htm#1041419
    to check how it does.
    The API for the package DBMS_XMLDOM is given on the same page(http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/appdev.920/a96620/xdb08pls.htm#1040676)
    You can use them for your requirement.
    Regards,
    Anupama

  • Counting xml elements using javascript

    How can I count the number of certain xml elements inside the xml file that import.
    Example xml:
    <list>
         <product>
              <name>Product_01</name>
              <detail>info here</detail>
         </product>
         <product>
              <name>Product_02</name>
              <detail>info here</detail>
         </product>
         <product>
              <name>Product_03</name>
              <detail>info here</detail>
         </product>
    </list>
    I would like to count the number of product -elements in this example xml.
    I'm using javascript for scripting.
    Thanks.

    #target indesign
    #include "/Applications/Adobe InDesign CS3/Scripts/Xml Rules/glue code.jsx"
    var myDocument = app.activeDocument;
    var myCounter = 0;
    var myRuleSet = new Array (new ProcessProduct);
    with(myDocument){
        var elements = xmlElements;
        __processRuleSet(elements.item(0), myRuleSet);
    alert("Found " + myCounter + " product elements");
    function ProcessProduct(){
        this.name = "ProcessProduct";
        this.xpath = "//product";   
        this.apply = function(myElement, myRuleProcessor){
            with(myElement){
                myCounter++;
        return true;

  • Remove xml element using JS[CS3]

    Hi, I have an xml structure where i want to remove some paritcular element named "extlink".
    I do have one script with me but it doesn't wipe out all specific xml element from structure.
    var myDoc = app.activeDocument;
    var foundtext = 0
    Query_Remove (myDoc);
    alert ("You have removed " + foundtext + " " +" Link !!")
    exit (0);
    function Query_Remove(elm)
    try
    for(var i=elm.xmlElements.length-1; i>=0; i--)
         if((elm.xmlElements[i].markupTag.name == "extlink") && (elm.xmlElements[i].xmlElements[0].markupTag.name == "http"))
        var Store_CitAttri = elm.xmlElements[i].xmlElements[0].xmlAttributes.item("c_style").value;
         if(Store_CitAttri == "URL")
          elm.xmlElements[i].remove();
         foundtext = foundtext + 1;
       Query_Remove(elm.xmlElements[i]);
    catch (e){
    Some time it skip the element from all figure captions and some time from body text and some time it works perfectly
    Could any one figure it out why this script behaviour is not consistent as i am new to scripting and not getting any idea about this.
    Thanks
    Mac

    Okay, after peering over your code and trying a few things out I see one immediate problem and one possible improvement.
    The problem lies in this:
    1. if condition is true, remove item
    2. check recursively
    The problem is .. if an item is removed, the following recursive check will always fail. However, the entire loop is wrapped into a try..catch, so InDesign will not alert you that it failed. Instead, it will continue with what's after the loop, exactly because the try..catch is around the entire loop!
    Change the loop code to this
    if((elm.xmlElements[i].markupTag.name == "http") && (elm.xmlElements[i].parent.markupTag.name == "extlink"))
        var Store_CitAttri = elm.xmlElements[i].xmlAttributes.item("c_style").value;
        if(Store_CitAttri == "URL")
          elm.xmlElements[i].remove();
           foundtext = foundtext + 1;
           continue;
    Query_Remove(elm.xmlElements[i]);
    so the recursive checking is skipped. You can also remove the entire try..catch block, as this may hide additional errors ...
    The improvement is: as I started reading this thread from the top again, shouldn't you be removing the "extlink" items, rather than just the "http" ones inside?
    If so, remove the parent of the found item (which is always the "extlink"):
          elm.xmlElements[i].parent.remove();
    -- and, as this will break the loop (because you just removed the set of elements it was working in!), replace 'continue' with 'return'.
    Hope this helps

  • How to modify an XML values using XSLT and Java

    Hi Friends,
    I wish to modify a simple xml to another xml using XSLT, please let me know what are the things i need to know to convert the XML to another XML.
    If somebody can give a sample code, it will be great...
    I wish to do the following sample conversion of XML
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <ROOT>
    <NAME>TEST1</NAME>
    </ROOT>so that the results look like below....
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <ROOT>
    <NAME>TEST2</NAME>
    </ROOT>Notice TEST1 is replaced with TEST2 in the 2nd XML, I wish to get that result...please help.
    Thanks and Regards,
    JG

    Thanks for your nice reply... do you have a sample code...

  • Split XML file using SAX

    Hello
    Can some one tell me How do I go about splitting a large XML int smaller files using the SAX Parser.
    I have ruled out the use of dom taking memory overhead into consideration.
    I should be able to pass the number of records that go into each files
    dynamically.
    If some one can share their code snippet, that would be great
    cheer
    rachans

    I need each split file to be well formed, its not just chopping the big file into pieces...
    the structure of large file is something like this
    <root>
    <header>
    </header>
    <body>
    <records>
    </records>
    <records>
    </records>
    </body>
    </root>
    now the split file looks like this
    <root>
    <header>
    </header>
    <body>
    <records>
    </records>
    </body>
    </root>
    I will need to split by a number, if say 2 then each file will have 2 records.....the header is the same for all files...hope this explanation helps..

  • Formatting of query returning multiple xml elements using xmlattributes

    Hi, i've been tasked with producing output, based on an XSD, with repeating elements defined using distinct attributes related to the element. I've managed to get this working, but would like to make the solutions code more elegant than it is at the moment, and was wondering if anyone may be able to give me a hand with this?
    Firstly, database details
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    "CORE     11.2.0.2.0     Production"
    TNS for IBM/AIX RISC System/6000: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - ProductionAn example of the output i'm expecting is as follows
    <financials>
              <depositDate INVITE_PACK="Current">2011-12-01</depositDate>
              <depositDate INVITE_PACK="Alternate">2011-12-01</depositDate>
              <deposit INVITE_PACK="Current">19.88</deposit>
              <deposit INVITE_PACK="Alternate">20.65</deposit>
              <basicPremium INVITE_PACK="Current">198.76</basicPremium>
              <basicPremium INVITE_PACK="Alternate">206.49</basicPremium>
    </financials>This data is held in a relational database table and i'm currently gernerating the data from this relational table using something similar to the following:
    SELECT xmlagg
           (xmlelement("financials",
                       (select xmlagg(xmlelement("depositDate",
                                                 xmlattributes(fi1.quote),
                                                 fi1.DEPOSIT_DATE
                                                 )) as "depDt_det"
                          FROM (select distinct f1.fulfilment_queue_key,
                                                f1.fq_policy,
                                                f1.quote,
                                                f1.deposit_date
                                  from staging.fulfilment_xml_finance_inv1 f1) fi1
                         WHERE fi1.fulfilment_queue_key = fi.fulfilment_queue_key),
                       (select xmlagg(xmlelement("deposit",
                                                 xmlattributes(fi1.quote),
                                                 fi1.PPD_DEPOSIT)) as "dep_det"
                          FROM (select distinct f1.fulfilment_queue_key,
                                                f1.fq_policy,
                                                f1.quote,
                                                f1.PPD_DEPOSIT
                                  from staging.fulfilment_xml_finance_inv1 f1) fi1
                         WHERE fi1.fulfilment_queue_key = fi.fulfilment_queue_key),
                       (select xmlagg(xmlelement("basicPremium",
                                                 xmlattributes(fi1.quote),
                                                 fi1.BASIC_PREM)) as "bprem_det"
                          FROM (select distinct f1.fulfilment_queue_key,
                                                f1.fq_policy,
                                                f1.quote,
                                                f1.basic_prem
                                  from staging.fulfilment_xml_finance_inv1 f1) fi1
                         WHERE fi1.fulfilment_queue_key = fi.fulfilment_queue_key)                                                                                                                                                                                                           
      FROM staging.fulfilment_xml_finance_inv1 fi
      WHERE fi.fulfilment_queue_key = 2861
       AND rownum = 1As can be seen, i'm replicating a number of calls to the fulfilment_xml_finance_inv1 table. I was wondering if there is a way to do the above in a more succinct, supportable and readable fashion? I have a tried a number of differnt methods to do this, but can't seem to get it to work for me. Any ideas would be greatly appreciated.
    Thanks.

    Hi again,
    No problem, create table statement
    -- Create table
    create table FULFILMENT_XML_FINANCE_INV1
      fulfilment_queue_key          NUMBER(22),
      fq_policy                     VARCHAR2(50),
      riskversion                   NUMBER(28,7),
      basic_prem                    NUMBER(10,2),
      os_balance                    NUMBER(10,2),
      ppd_deposit                   NUMBER(10,2),
      ppd_plan_charge               NUMBER(10,2),
      ppd_charge_for_interest       NUMBER(10,2),
      ppd_apr_perc                  NUMBER(10,2),
      ppd_interest                  NUMBER(22,6),
      inst_freq                     VARCHAR2(1),
      deposit_date                  DATE,
      adj_premium                   NUMBER(19,2),
      order1                        NUMBER(38),
      amountdue                     NUMBER(28,7),
      collection_date               DATE,
      paymentduedate                DATE,
      scharges                      NUMBER(19,2),
      ppd_plan_collection_reference VARCHAR2(20),
      reapply_date                  DATE,
      reapply_amount                NUMBER(19,2),
      last_inst_freq                VARCHAR2(1),
      quote                         VARCHAR2(10)
    );example inserts
    insert into fulfilment_xml_finance_inv1
       (fulfilment_queue_key,
    fq_policy,
    riskversion,
    basic_prem,
    os_balance,
    ppd_deposit,
    ppd_plan_charge,
    ppd_charge_for_interest,
    ppd_apr_perc,
    ppd_interest,
    inst_freq,
    deposit_date,
    adj_premium,
    order1,
    amountdue,
    collection_date,
    paymentduedate,
    scharges,
    ppd_plan_collection_reference,
    reapply_date,
    reapply_amount,
    last_inst_freq,
    quote)
    values
    (2861,
    'TEST1234',
    3,
    198.76,
    123.45,
    19.88,
    0,
    99.99,
    99.99,
    55.55,
    'A',
    to_date('01/12/2011','dd/mm/yyyy'),
    null,
    NULL,
    NULL,
    NULL,
    null,
    0.00,
    'N/A',
    NULL,
    NULL,
    'A',
    'Current')
    insert into fulfilment_xml_finance_inv1
       (fulfilment_queue_key,
    fq_policy,
    riskversion,
    basic_prem,
    os_balance,
    ppd_deposit,
    ppd_plan_charge,
    ppd_charge_for_interest,
    ppd_apr_perc,
    ppd_interest,
    inst_freq,
    deposit_date,
    adj_premium,
    order1,
    amountdue,
    collection_date,
    paymentduedate,
    scharges,
    ppd_plan_collection_reference,
    reapply_date,
    reapply_amount,
    last_inst_freq,
    quote)
    values
    (2861,
    'TEST1234',
    3,
    206.49,
    123.45,
    20.65,
    0,
    99.99,
    99.99,
    55.55,
    'A',
    to_date('01/12/2011','dd/mm/yyyy'),
    null,
    NULL,
    NULL,
    NULL,
    null,
    0.00,
    'N/A',
    NULL,
    NULL,
    'A',
    'Alternate') Hope this is what you were after, please let me know if you need anything else.
    Thanks again.

  • How to replace XML elements using java

    I have been usint SAX 2.0 and DOM Level 2 api's to represent XML documents, which i parse with apache's Xerces parser... I am trying to delete certain elements and replace them with others, but none of the api's allow this the closes i have come is replacing attributes of elements....

    Answered in crosspost.
    http://forum.java.sun.com/thread.jspa?threadID=638156

Maybe you are looking for

  • Restored my iMac from Time Machine now Hard Drive has doubled! Need Space!

    I Restored my new (refurbished) iMac 2010 (Snow Leopard 10.6.4) from Time Machine now the Hard Drive has doubled 450GB to 900GB. I want to recover the space on my hard drive, What do I do? Side Note: My previous iMac (2007) died so I went and bought

  • Problems with some photos when converting Publisher files to PDF using Acrobat 9

    I tried to make a pdf of a publisher document that has a number of photographs. Two of the photographs appear grey with streaks -looks like some of the colours are not converting properly. The same document works fine with Acrobat 8 but not with vers

  • Beta or not ?

    Hello everybody, I would only like to know if the JavaTM 2 SDK, Standard Edition,v 1.4.0 Release Candidate (J2SETM) is a beta version or not ? Thanks in advance.

  • Copy URL to clipboard

    Having switched from Mozilla to Safari I am finding a small frustration copying a web address (URL) from the Safari address field to the clipboard. With Mozilla one click in the field would select the whole address - which is then easily copied with

  • Modeling a Many to Many relationship

    How can I modeling a Many to Many relationship between a fact table and a dimensión in Essbase? For example I have a economic zone dimension and a record in the fact is just related to one country... but a country is related to many economic zone...