Sorting XMLListCollection by nested elements

I've been sorting XML files using an XMLListCollection when I have an XML with the following structure:
<products>
     <product id="1">
          <field1>value</field1>
          <field2>value</field2>
          <field3>value</field3>
     </product>
     <product id="2">
          <field1>value</field1>
          <field2>value</field2>
          <field3>value</field3>
     </product>
</products>
by using an XMLListCollection as follows:
var mySort:sort = new Sort();
var xlcProducts:XMLListCollection = new XMLListCollection();
mySort.fields = [new SortField("field3"), new SortField("field2")]
xlcProducts.source = dataSet.elements("product");
xlcProducts.sort = mySort;
xlcProducts.refresh();
Now I'm dealing with a more complicated XML that follows this structure:
<products>
     <product>
          <productID>607</productID>
          <productName>ADS1000</productName>
          <features>
               <featureData>
                    <featureName>feature1</featureName>
                    <featureValue>value1</featureValue>
               </featureData>
               <featureData>
                    <featureName>feature2</featureName>
                    <featureValue>value2</featureValue>
               </featureData>
               <featureData>
                    <featureName>feature3</featureName>
                    <featureValue>value3</featureValue>
               </featureData>
          </features>
     </product>
     <product>
          <productID>607</productID>
          <productName>ADS1000</productName>
          <features>
               <featureData>
                    <featureName>feature1</featureName>
                    <featureValue>value1</featureValue>
               </featureData>
               <featureData>
                    <featureName>feature2</featureName>
                    <featureValue>value2</featureValue>
               </featureData>
               <featureData>
                    <featureName>feature3</featureName>
                    <featureValue>value3</featureValue>
               </featureData>
          </features>
     </product>
</products>
My problem here is that the same approach doesn't seem to work, when I create the mySort object to assign to the XMLListCollection I can't seen to be able to point it to a field that is not on the top level of the XML's children. Here, I need to sort the XML by featureValue for two different features (which will change at different points in time)
I've tried to do stuff like this to no avail:
mySort.fields = [new SortField("features.featureData.(featureName == \"feature3\").featureValue"), new SortField("features.featureData.(featureName == \"feature2\").featureValue")]
I'm assuming I can't have XML queries in the SortField's name, but nothing else I've tried has worked.

Yeah, I actually started working on that approach earlier today.
Thanks for the confirmation.

Similar Messages

  • Question about xml schemas and the use of unqualified nested elements

    Hello,
    I have the following schema:
    <?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns="http://xml.netbeans.org/examples/targetNS"
        targetNamespace="http://xml.netbeans.org/examples/targetNS"
        elementFormDefault="unqualified">
        <xsd:element name="name" type="xsd:string"/>
        <xsd:element name="age" type="xsd:int"/>
        <xsd:element name="person">
            <xsd:complexType>
                <xsd:sequence>
                    <xsd:element ref="name"/>
                    <xsd:element ref="age"/>
                   <xsd:element name="height" type="xsd:int"/>
                </xsd:sequence>
            </xsd:complexType>
        </xsd:element>
    </xsd:schema>I am just wondering why would someone have a nested element that is unqualified? here the "height" element.
    Can anyone explain this to me please?
    Thanks in advance,
    Julien.
    here is an instance xml document
    <?xml version="1.0" encoding="UTF-8"?>
    <person xmlns='http://xml.netbeans.org/examples/targetNS'
      xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
      xsi:schemaLocation='http://xml.netbeans.org/examples/targetNS file:/E:/dev/java/XML/WebApplicationXML/web/newXMLSchemaThree.xsd'>
    <name>toto</name>
    <age>40</age>
    <height>180</height>
    </person>

    Don't worry about it.
    There are two different styles of schemas. In one style, you define the elements, attributes, etc. at the top, and then use the "ref" form to refer to them. (I call this the "global" style.) The other style is to define elements inline where they are used. ("local" style)
    Within some bounds, they work the same and which you use is a choice of you and the tools that generate the schemas.
    A warning about the local style. It is possible to define an element in two different locations in the schema that are different. It will get past all schema validation, but it seems wrong to my sense of esthetics. With the global style, this will not happen.
    So, how did this happen? Probably one person did the schema when it only had a name and age. Then, someone else added the height element. They either used a different tool, or preferred the other style. I'm aware of no difference in the document you have described between the two styles.
    Dave Patterson

  • Specifying nested element with two different XML Schema

    Hello,
    I am trying to convert one xml file to another file. I figure data services would be great for this.
    My problem relates to how to have a source xml file with a certain xml schema be transformed to one of a different xml schema. I cannot build the nested elements of the target schema.
    From the source xml I only need four fields. But they need to be nested three levels in the target xml.
    Source
    <DRUG_PRODUCT_LST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <DRUG_ITEM>
          <DRUG_PRODUCT_ID>113083</DRUG_PRODUCT_ID>
          <DIN_PDIN>2317559</DIN_PDIN>
          <HC_BRAND_NAME>PMS-SILDENAFIL</HC_BRAND_NAME>
          <HC_ATC_CODE>G04BE03</HC_ATC_CODE>
       </DRUG_ITEM>
    <DRUG_PRODUCT_LST
    Target
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <CODES>
       <CODE_TYPES>
          <CODE_TYPE>
             <COD_CODE>113083</COD_CODE>
             <COD_DESCR>PMS-SILDENAFIL</COD_DESCR>
             <COD_SOURCE>G04BE03</COD_SOURCE>
             <COD_NPSA>2317559</COD_NPSA>
          </CODE_TYPE>
       </CODE_TYPES>
    </CODES>
    I have tried using an xml pipline to unnest the source, then use a query transform to re-nest for the target. But I do not know how to specify the input schemas.

    Hello,
    I am trying to convert one xml file to another file. I figure data services would be great for this.
    My problem relates to how to have a source xml file with a certain xml schema be transformed to one of a different xml schema. I cannot build the nested elements of the target schema.
    From the source xml I only need four fields. But they need to be nested three levels in the target xml.
    Source
    <DRUG_PRODUCT_LST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <DRUG_ITEM>
          <DRUG_PRODUCT_ID>113083</DRUG_PRODUCT_ID>
          <DIN_PDIN>2317559</DIN_PDIN>
          <HC_BRAND_NAME>PMS-SILDENAFIL</HC_BRAND_NAME>
          <HC_ATC_CODE>G04BE03</HC_ATC_CODE>
       </DRUG_ITEM>
    <DRUG_PRODUCT_LST
    Target
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <CODES>
       <CODE_TYPES>
          <CODE_TYPE>
             <COD_CODE>113083</COD_CODE>
             <COD_DESCR>PMS-SILDENAFIL</COD_DESCR>
             <COD_SOURCE>G04BE03</COD_SOURCE>
             <COD_NPSA>2317559</COD_NPSA>
          </CODE_TYPE>
       </CODE_TYPES>
    </CODES>
    I have tried using an xml pipline to unnest the source, then use a query transform to re-nest for the target. But I do not know how to specify the input schemas.

  • Xml-fragment Issue retrieving Nested element data

    Hi,
    I've problem retrieving the nested element data from the xml. Using XmlBeans I am getting null when retriving the inner element. I printed the nested element xmlobject it has Xml-Fragment wrapped. I tired using below code it doesn't throw any error but the data is lost
    AAAA TempObj=AAAA.getBXXX().getCXXX(0);
    //remove xml fragment
    XmlOptions xmlOpt = new XmlOptions();
    xmlOpt.setSaveOuter();
    XmlCursor c= TempObj.newCursor();
    c.toFirstChild();
    Myclass myclassObj= Myclass.Factory.parse(c.getObject().xmlText(xmlOpt));
    log.debug("Records: "+myclassObj .getXXArray().length);
    Output:
    length should give aleast 1 or more but I am getting 0. That means the xmltext didn't parse properly.
    Can anybody suggest what could be the problem.
    Thanks in advance.
    -Sri

    no answer

  • Extracting nested element text

    Hi everyone,
    I have a basic question which has been on my mind for a few days now. I'd be appreciative for any assistance or advice.
    I'm aiming to extract info using JDOM from all the children of 'Parent' (please see code below). Getting info/text from 'ChildOne' and 'ChildTwo' is easy, but I am having trouble extracting info out of the nested-element at 'ChildThree'.
    I'd be appreciative if anyone can shed light on how to solve such a question: how to not only extract info out of ChildOne, Two but also ChildThree, knowing that ChildThree is nested.
    I've playing around with instantiating an element which gets the children of 'ChildThree' and another which gets the elements of 'ChildThree/'FirstChild'... but I think there's an easier way than that!!
    I've attached a code-snippet which is resembles my XML file. I'd be very appreciative for any advice.
    Thanks,
    p
      <Root>
        <Parent>
          <ChildOne>First</ChildOne>
          <ChildTwo>Second</ChildTwo>
          <ChildThree>
            <InnerChild>
              <First>Text</First>
              <Second>Text</Second>
              <Third>Text</Third>
            </InnerChild>
          </ChildThree>
        </Parent>
      <Root>

    I reached a solution to my problem actually.
    In case other people have the same problem, this is what I did; source-attached.
    I made a behavior called 'displayElements' and it takes a parameter of type Element. I then made it so that for this specific element, I call the '.getChildren()' behavior such that a List is produced. This List was then saved as an Iterator and read-through iteratively.
    At the end, I re-called the 'displayElements' method and passed-in the same element because that element MIGHT have inner-elements.
    Anyways, enough talk. Here's my code incase other people have the same problem.
    public static void displayKids(Element current) {
              //Printing the current-element and the corresponding element-text
              System.out.println(current.getName() + "\t" + current.getTextTrim());
              //Print a row of stars; increases readability
              System.out.println("********************************");
              //For the specific element, we then call 'getters' which get the
              //children for that specific element and save as type 'List'
              List<Element> children = current.getChildren();
              Iterator iterator = children.iterator();
              while (iterator.hasNext()) {
                   Element child = (Element) iterator.next();
                   //Recursively calling the function
                   displayKids(child);
         }

  • XML self referred nested element error in Data Services

    Hi,
    I am using BO Data services for data transfer. I am having an error while transferring data from xml file to database. Here is the scenario:
    When i execute the job i get the error that an element "CategoryList" found in xml file but not found in the schema used to build the ETL plan.
    i dig into that and found out that "CategoryList" is self referential. For example the CategoryList has a nested element Category, and Category has a nested element CategoryList; which makes CategoryList self referred indirectly. when i don't have this self referential mechanism the data transfer work fine with the same xml and xsd files.
    Is there any special way to deal with this?
    Thanks
    Umer

    Not sure if you have already got the answer, use "URI" not
    "URL".

  • Controlling Element Tags using Nested Elements

    When I use the below I get:
    <?xml version = '1.0'?>
    <FSAATLAS>
    <STUDENT>
    <OBJECT_NAME>ADDRESS_T</OBJECT_NAME>
    <INNER_ELEMENT>
    <INNER_ELEMENT_ROW num="1">
    <DUMMY>X</DUMMY>
    </INNER_ELEMENT_ROW>
    </INNER_ELEMENT>
    </STUDENT>
    </FSAATLAS>
    How do I get the INNER_ELEMENT_ROW and num="1" from
    appearing in the NESTED ELEMENT!!!
    Best Regards,
    James Colestock
    import java.sql.*;
    import oracle.jdbc.OracleDriver;
    import oracle.xml.sql.query.*;
    import org.w3c.dom.*;
    import oracle.xml.parser.v2.*;
    public class XML {
    public XML() {
    private static final String QUERY = "select object_name, CURSOR(select dummy as dummy from dual) as INNER_ELEMENT from user_objects";
    public static void main(String[] args) throws Throwable {
    Connection c = getConnection();
    OracleXMLQuery q = new OracleXMLQuery(c,QUERY);
    q.setCollIdAttrName("");
    q.setCollIdAttr("");
    q.setRowIdAttrName("");
    q.setRowIdColumn("");
    q.setRowsetTag("FSAATLAS");
    q.setRowTag("STUDENT");
    q.useNullAttributeIndicator(false);
    q.useTypeForCollElemTag(false);
    String s = q.getXMLString();
    System.out.println(s);
    q.close();
    /*q = new OracleXMLQuery(c,QUERY);
    s = q.getXMLMetaData(OracleXMLQuery.SCHEMA,false);
    System.out.println(s);
    q.close();
    q = new OracleXMLQuery(c,QUERY);
    Document d = q.getXMLDOM(OracleXMLQuery.SCHEMA);
    ((XMLDocument)d).print(System.out);
    q.close();
    q = new OracleXMLQuery(c,QUERY);
    s = q.getXMLString(OracleXMLQuery.SCHEMA);
    System.out.println(s);*/
    public static Connection getConnection() throws SQLException {
    String username = " james";
    String password = "masterjames";
    String thinConn = "jdbc:oracle:thin:@localhost:1526:PORTLAND";
    Driver d = new OracleDriver();
    return DriverManager.getConnection(thinConn,username,password);
    }

    When I use the below I get:
    <?xml version = '1.0'?>
    <FSAATLAS>
    <STUDENT>
    <OBJECT_NAME>ADDRESS_T</OBJECT_NAME>
    <INNER_ELEMENT>
    <INNER_ELEMENT_ROW num="1">
    <DUMMY>X</DUMMY>
    </INNER_ELEMENT_ROW>
    </INNER_ELEMENT>
    </STUDENT>
    </FSAATLAS>
    How do I get the INNER_ELEMENT_ROW and num="1" from
    appearing in the NESTED ELEMENT!!!
    Best Regards,
    James Colestock
    import java.sql.*;
    import oracle.jdbc.OracleDriver;
    import oracle.xml.sql.query.*;
    import org.w3c.dom.*;
    import oracle.xml.parser.v2.*;
    public class XML {
    public XML() {
    private static final String QUERY = "select object_name, CURSOR(select dummy as dummy from dual) as INNER_ELEMENT from user_objects";
    public static void main(String[] args) throws Throwable {
    Connection c = getConnection();
    OracleXMLQuery q = new OracleXMLQuery(c,QUERY);
    q.setCollIdAttrName("");
    q.setCollIdAttr("");
    q.setRowIdAttrName("");
    q.setRowIdColumn("");
    q.setRowsetTag("FSAATLAS");
    q.setRowTag("STUDENT");
    q.useNullAttributeIndicator(false);
    q.useTypeForCollElemTag(false);
    String s = q.getXMLString();
    System.out.println(s);
    q.close();
    /*q = new OracleXMLQuery(c,QUERY);
    s = q.getXMLMetaData(OracleXMLQuery.SCHEMA,false);
    System.out.println(s);
    q.close();
    q = new OracleXMLQuery(c,QUERY);
    Document d = q.getXMLDOM(OracleXMLQuery.SCHEMA);
    ((XMLDocument)d).print(System.out);
    q.close();
    q = new OracleXMLQuery(c,QUERY);
    s = q.getXMLString(OracleXMLQuery.SCHEMA);
    System.out.println(s);*/
    public static Connection getConnection() throws SQLException {
    String username = " james";
    String password = "masterjames";
    String thinConn = "jdbc:oracle:thin:@localhost:1526:PORTLAND";
    Driver d = new OracleDriver();
    return DriverManager.getConnection(thinConn,username,password);
    }

  • Who to query and join nested elements

    I have a table that contains a XMLTYPE Field. How do I query and join nested elements. For example I have a schema that has a PerstrenList element that holds one or more Perstren nodes.  The Perstren node will contain a RemarksList node that can contain one or more Remarks nodes.  My goal is to query all of the Remarks and join them with the information in it's parent node. Without the parent node information the remark is meaningless.  Following is a example document and desire result set. I know how to query the Perstren or the Remarks I just can not figure out how to marry the two. The query should only return the remarks joined with the parent information.
    <RasDataSet>
       <PerstrenList>
            <Perstren>
               <TPERS>A</TPERS>
               <DEPLY>B</DEPLY>
               <STRUC>5</STRUC>
               <RemarksList>
                   <REMARK>
                        <LABEL>ABC</LABEL>
                        <GENTEXT>Hello world</GENTEXT>
                   </REMARK>
                   <REMARK>
                        <LABEL>XYZ</LABEL>
                        <GENTEXT>Oracle XML</GENTEXT>
                   </REMARK>
               <RemarksList>
            </Perstren>
            <Perstren>
           <TPERS>C</TPERS>
           <DEPLY>D</DEPLY>
           <STRUC>4</STRUC>
           <RemarksList>
               <REMARK>
                    <LABEL>EFG</LABEL>
                    <GENTEXT>Database</GENTEXT>
               </REMARK>
           <RemarksList>
            </Perstren>
            <Perstren>
           <TPERS>E</TPERS>
           <DEPLY>F</DEPLY>
           <STRUC>3</STRUC>
            </Perstren>       
       <PerstrenList>
    </RasDataSet>
    desired Results
    TPERS  DEPLY   LABEL  GENTEXT
    A       B       ABC   Hello World
    A       B       XYZ   Oracle XML
    C       D       EFG   Database
    select uic,
            extractvalue(Column_value,'/Perstren/TPERS') as TPERS,
            extractvalue(Column_value,'/Perstren/DEPLY') as DEPLY,
            extractvalue(Column_value,'/Perstren/SECUR') as SECUR,
            extractvalue(Column_value,'/Perstren/STRUC') as STRUC,
            extractvalue(Column_value,'/Perstren/TIME') as TIME,
            extractvalue(Column_value,'/Perstren/AUTH') as AUTH,
            extractvalue(Column_value,'/Perstren/ASGD') as ASGD,
    from test_ref doc,
        table(XMLSequence(extract(doc.XML_DOC,'/RasDataSet/PerstrenList/Perstren'))) per
    [pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Sorry my Pre tag was in the wrong place Text reads:
    I have a table that contains a XMLTYPE Field. How do I query and join nested elements. For example I have a schema that has a PerstrenList element that holds one or more Perstren nodes. The Perstren node will contain a RemarksList node that can contain one or more Remarks nodes. My goal is to query all of the Remarks and join them with the information in it's parent node. Without the parent node information the remark is meaningless. Following is a example document and desire result set. I know how to query the Perstren or the Remarks I just can not figure out how to marry the two. The query should only return the remarks joined with the parent information.
    Sorry my Pre tag was in the wrong place

  • Loop through nested elements and insert via PL/SQL

    INSERT INTO Orders(id, OrderXML) VALUES
    (S_Orders.Nextval,
    '<?xml version="1.0" encoding="utf-8" ?>
    <Order xmlns="urn:foo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:foo foo-1.xsd">
    <OrderRef>BBB</OrderRef>
    <OrderDate>2005-03-29</OrderDate>
    <CustomerID>1051</CustomerID>
    <Items>
    <Item>
    <ProductID>7</ProductID>
    <Price>45.6</Price>
    <Quantity>2</Quantity>
    </Item>
    <Item>
    <ProductID>19</ProductID>
    <Price>73.5</Price>
    <Quantity>10</Quantity>
    </Item>
    </Items>
    </Order>'
    I some questions regarding index search of nested elements like,Items in the above example.
    I would like to know how I can LOOP through the Items like 1..2 LOOP
    and insert those elements(item) into one table. Order information should go in to another table.
    Can this be done with xpath and PL/SQL.
    Regards
    Ulf

    Hi Marco!
    Here's some more information:
    CREATE TABLE ITEM (ProductID NUMBER,
    Price NUMBER(8,2)
    Quantity 10 NUMBER);
    CREATE TABLE ORDER (OrderRef VARCHAR2(10),
    ORDER_DATE VARCHAR2(10),
    CUSTOMERID NUMBER);
    The main problem that I have is to create an solution that can be dynamic so that I can have for instance one order and four items in one XML.
    The second XML can have one order and 10 items.
    First I want to insert the order elements in the order table and then the items records in the item table.
    To complicate things futher my real XML have namespaces in the XML, but this I think I can handle.
    Summary: So for each order row(element) I want to traverse the Item elements and insert them to the Item table.
    Regards
    /Ulf

  • JTable sorting - problem when adding elements (complete code inside)

    I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
    Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
    Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
    The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
    I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
    Thanks a lot
    3 files:
    (1) TableSorterDemo
    (2) Traveler
    (3)TableSorter
    //TableSorterDemo:
    package sorter;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * TableSorterDemo is like TableDemo, except that it
    * inserts a custom model -- a sorter -- between the table
    * and its data model.  It also has column tool tips.
    public class TableSorterDemo implements ActionListener
         private JPanel superPanel;
         private JButton clickMe = new JButton("click me to get diff data");
         private boolean DEBUG = false;
         private DefaultListModel defaultListModel;
         private JTable table;
        public TableSorterDemo()
             superPanel = new JPanel(new BorderLayout());
             defaultListModel = new DefaultListModel();
             init1();
            TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS     
            table = new JTable(sorter);             //NEW
            sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Set up tool tips for column headers.
            table.getTableHeader().setToolTipText(
                    "Click to specify sorting; Control-Click to specify secondary sorting");
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            superPanel.add("Center", scrollPane);
            superPanel.add("South",clickMe);
            clickMe.addActionListener(this);              
        public JPanel getPanel()
             return superPanel;
        public void init1()
             //in real life this will be done from the db
             Traveler a = new Traveler();
             Traveler b = new Traveler();
             Traveler c = new Traveler();
             a.setFirstName("Elvis");
             a.setLastName("Presley");
             a.setSprot("Ping Pong");
             a.setNumYears(3);
             a.setVegetarian(true);
             b.setFirstName("Elton");
             b.setLastName("John");
             b.setSprot("Soccer");
             b.setNumYears(2);
             b.setVegetarian(true);
             c.setFirstName("shaquille");
             c.setLastName("oneil");
             c.setSprot("Golf");
             c.setNumYears(22);
             c.setVegetarian(true);
             defaultListModel.addElement(a);
             defaultListModel.addElement(b);
             defaultListModel.addElement(c);
        public void init2()
             //in real life this will be done from the db
             Traveler d = new Traveler();
             Traveler e = new Traveler();
             Traveler f = new Traveler();
             Traveler g = new Traveler();
             d.setFirstName("John");
             d.setLastName("Smith");
             d.setSprot("Tennis");
             d.setNumYears(32);
             d.setVegetarian(true);
             e.setFirstName("Ron");
             e.setLastName("Cohen");
             e.setSprot("Baseball");
             e.setNumYears(12);
             e.setVegetarian(true);
             f.setFirstName("Donald");
             f.setLastName("Mac Novice");
             f.setSprot("Vallyball");
             f.setNumYears(1);
             f.setVegetarian(true);
             g.setFirstName("Eithan");
             g.setLastName("Superstar");
             g.setSprot("Vallyball");
             g.setNumYears(21);
             g.setVegetarian(true);
             defaultListModel.addElement(d);
             defaultListModel.addElement(e);
             defaultListModel.addElement(f);
             defaultListModel.addElement(g);            
        class MyTableModel extends AbstractTableModel
             private DefaultListModel myModel;
             public MyTableModel(DefaultListModel m)
                  myModel=m;
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return myModel.size();
            public String getColumnName(int column)
                 return getNames()[column];             
             public String[] getNames()
                  String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
                  return names;
            public Object getValueAt(int row, int col)
                 return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
            public Object distributeObjectsInTable(int row, int col, Traveler tr)
               switch(col)
                         case 0:
                              return tr.getFirstName();
                         case 1:
                           return tr.getLastName();
                      case 2:
                           return tr.getSprot();
                      case 3:
                           return new Integer(tr.getNumYears());
                      case 4:
                           return new Boolean (tr.isVegetarian());
                     default:
                         return "Error";
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableSorterDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableSorterDemo newContentPane = new TableSorterDemo();
            newContentPane.getPanel().setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane.getPanel());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()                   
                public void run()
                    createAndShowGUI();
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==clickMe)
                   defaultListModel.removeAllElements();
                   init2(); //if the size of the model was less than 2 items - the result will be ok.
                              //in other words, if you commens the last 2 rows of this method (addElement(f) & g)
                             // the result will be fine.
                   table.updateUI();          
    }//(2) Traveler
    package sorter;
    public class Traveler
         private String firstName;
         private String lastName;
         private String sprot;
         private int numYears;
         private boolean vegetarian;
         public String getFirstName()
              return firstName;
         public String getLastName()
              return lastName;
         public int getNumYears()
              return numYears;
         public String getSprot()
              return sprot;
         public boolean isVegetarian()
              return vegetarian;
         public void setFirstName(String firstName)
              this.firstName = firstName;
         public void setLastName(String lastName)
              this.lastName = lastName;
         public void setNumYears(int numYears)
              this.numYears = numYears;
         public void setSprot(String sprot)
              this.sprot = sprot;
         public void setVegetarian(boolean vegetarian)
              this.vegetarian = vegetarian;
    }//(3)TableSorter
    package sorter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    public class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView()
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

    The table listens to the TableModel for changes. Changing the table by adding/removing
    rows or columns has no affect on its table model. If you make changes to the table model
    the table will be notified by its TableModelListener and change its view. So tell
    MyTableModel about the change of data:
    public class TableSorterDemo implements ActionListener
        MyTableModel tableModel;
        public TableSorterDemo()
            defaultListModel = new DefaultListModel();
            init1();
            tableModel = new MyTableModel(defaultListModel);
            TableSorter sorter = new TableSorter(tableModel);
        public void actionPerformed(ActionEvent ae)
            if (ae.getSource()==clickMe)
                defaultListModel.removeAllElements();
                init2();
                tableModel.fireTableStructureChanged();
    }

  • JAXB - nested elements of same name

    Hi
    I have a schema which can represent elements with identical nested names like this:
    <Simple>
    <Strong>
    <Simple/>
    </Strong>
    </Strong>
    The nesting is not recursive. i.e. the two 'Simple' elements are not actually identical. Unfortunately when I bind the schema to java using JAXB, the generated code won't compile and i get error due to name collision:
    "Nested type SimpleType hides an enclosing type"
    Can external binding fix this problem? I have already tried it but without success because there doesn't seem to be a way to bind the 'SimpleType' to another name. I can only change the interface name, but i need to change the type interface as well.
    I am tearing my hair about it and only solution i can see is that i use XSLT to transfrom the names before reading the XMl files in and writing them out. I can not change the original schema unfortunately.
    Any clues will be much appreciated, Martin.

    Hi everybody
    In the interest of anyone having similar problem, i have discovered that if i used a schema which used complex types explicitly (as generated by XmlSpy for me) the problem went away. This is probably because the nesting becomes irrelevant. My original schema contained only one element with all the types being anonymous and nested within that element.
    Regards, Martin.

  • General query to recurse through XML nested elements

    Hi all,
    Using 10g database...and I'm trying to parse XML (stored as clob, no registered schema) that handles nesting and reoccurring of the same element.
    i.e.
    <Policy ID="1">
    <Risk ID="1.1">
    <Risk ID="1.1.1">
    <Risk ID="1.1.1.1">
    </Risk>
    </Risk>
    </Risk>
    <Risk ID="1.2">
    </Risk>
    <Risk ID="1.3">
    <Risk ID="1.3.1">
    </Risk>
    </Risk>
    </Policy>
    The "Risk" element can be nested over and over again (and reoccur). Now, I want to combine each child, grandchild, great grandchild..... "Risk" element to the Policy element.
    i.e resultset has two columns - policyID, riskID
    Next, I'd like to be able to tie each Risk to it's parent Risk
    i.e. resultset has two columns - parentRiskID, childRiskID
    I know how to handle reoccurring and "known" hierarchies by using the XMLTYPE/PASSING techniques in the FROM clause but I'm struggling with the nesting part because I don't how deep it can go....This would seem to be fairly common in XML.
    Any ideas ?
    Thanks,
    Kevin

    Does this help
    SQL> var xmltext varchar2(4000)
    SQL> --
    SQL> begin
      2    :xmltext := '<Policy ID="1">
      3  <Risk ID="1.1">
      4  <Risk ID="1.1.1">
      5  <Risk ID="1.1.1.1">
      6  </Risk>
      7  </Risk>
      8  </Risk>
      9  <Risk ID="1.2">
    10  </Risk>
    11  <Risk ID="1.3">
    12  <Risk ID="1.3.1">
    13  </Risk>
    14  </Risk>
    15  </Policy>';
    16  end;
    17  /
    PL/SQL procedure successfully completed.
    SQL> select POLICY_ID, PARENT_RISK_ID, CHILD_RISK_ID
      2    from xmltable
      3         (
      4            '/Policy'
      5            passing xmltype(:xmltext)
      6            columns
      7            POLICY_ID number(4) path '@ID',
      8            RISKS     xmltype   path '//Risk'
      9         ) r,
    10         xmltable
    11         (
    12           '/Risk'
    13           passing RISKS
    14           columns
    15           PARENT_RISK_ID varchar2(40) path '@ID',
    16           CHILD_RISK_ID varchar2(40) path 'Risk/@ID'
    17         )
    18  /
    POLICY_ID PARENT_RISK_ID                           CHILD_RISK_ID
             1 1.1                                      1.1.1
             1 1.1.1                                    1.1.1.1
             1 1.1.1.1
             1 1.2
             1 1.3                                      1.3.1
             1 1.3.1
    6 rows selected.
    SQL> select POLICY_ID, PARENT_RISK_ID, CHILD_RISK_ID
      2    from xmltable
      3         (
      4            '/Policy'
      5            passing xmltype(:xmltext)
      6            columns
      7            POLICY_ID number(4) path '@ID',
      8            RISKS     xmltype   path '//Risk'
      9         ) r,
    10         xmltable
    11         (
    12           '/Risk'
    13           passing RISKS
    14           columns
    15           PARENT_RISK_ID varchar2(40) path '@ID',
    16           CHILD_RISK_ID varchar2(40) path 'Risk/@ID'
    17         )
    18   where CHILD_RISK_ID is not null
    19  /
    POLICY_ID PARENT_RISK_ID                           CHILD_RISK_ID
             1 1.1                                      1.1.1
             1 1.1.1                                    1.1.1.1
             1 1.3                                      1.3.1
    SQL>
    SQL>

  • Sort variant with WBS element...

    Dear All,
    I need to create a sort variant to use in AR01 report to capture the WBS element. But when i am creating the sort variant, it is saying this report can process tables only ANLAV, ANLB and ANLCV, here wbs element investment project field is there in ANLAV. but i want anothother field From ANLZ. What do i need to do...

    Hi,
    Hope you are looking for ANLZ fields.
    Go to OAVI and create your own sort version.
    There for WBS elemant, add table name as ANLZ and field name as PS_PSP_PNR2  /  IPSNR and press enter
    SAVE it.
    This will definetely work out.
    Thanks,
    Srinu

  • Sort array with equal elements

    Hi, I'm a new one.
    I have a problem to sort 2d array with equal elements (it has 5000000 of elements from 1-255) for example:
    1 2 1 1 3 4 5 5 6 1 2 3 (value from 1-255)
    2 2 1 1 3 3 3 3 4 4 4 1 (value from 1-255)
    And I need make array or matrix 255 rows vs 255 colomns, and count how many equal elements for example:
      1  2 3 4 5 6
    1 0 1 0 1 0 0
    2 0 1 0 1 0 0
    3 1 0 1 0 0 0 
    4 0 0 1 0 0 0
    5 0 0 2 0 0 0
    6 0 0 0 1 0 0
    I'll be happy if someone could help me

    I understand that it's very complicated explain.
    I build 2d array from two 1darray each of them has values 1-255. So right now i must constract array or matrix 255x255 where must calculat how many times value from (1-255) for one array in another array and write this sum for each value 1-255. I try to show it
    1 2                         so I need array 3x3; for first row for value 1 I have two times value 3 and one time value 2
    2 2                                                                                    2 I have two times value 1 and one time value 2 and one time value 3
    3 2                                                                                    3 I have two times value 2 and one time value 3 
    3 2              so my result matrix will be      1   2  3
    3 3                                                       1  0  1  2
    2 3                                                       2  2  1  1
    2 1                                                       3  0  2  3
    2 1
    1 3
    1 3
    Maybe its more clear

  • Can I sort on the second element of my vector?

    Sorry to intrude on the guru territory, but no one in the newbie camp has answered and I am sure someone over here has a quick answer...
    The first element is first name and the second is lastname. Right now I am using java.util.Collections.sort(v); This searches on the first name. I would like to search on the last name which is the second element. Any ideas?

    I'm not sure what's in your vector. I assume the vector contains strings, of the form "firstname lastname". In which case I suspect the default implemetation of sort is simply sorting the strings in the natural way. If you look at the second implementation of sort():
    sort(List l, Comparator c)
    you can implement your own comparator. The comparator is an interface tast you implement to compare two object the way you want th sorting done.
    so your comparator would implement compare to find the second word of each string (look at string tokenizer for this) and compare them (with String.compareTo). You need to do something similar with equals.
    So you call sort like this: sort(myVector,new MyComparator());
    Hope this helps.

Maybe you are looking for

  • OIM Active Directory 2008 integration

    Hi All, Has anyone integrated (or being in the process of integrating just now) OIM 9.1 with Active Directory on a Windows 2008 Server using the AD 9.1 connector or a custom connector? Any problems or other experiences with such integration? The 9.1.

  • Font sizing issues with JTextPane

    Hello all, I have a question which I hope won't be too difficult. Here is some background. I have created both a swing application that is a text editor. The user can cut, copy, and paste text. The user can also change the "font style" and "font size

  • Parameters in stored procedure

    If I need to call a stored procedure with 6 input parameters and 6 output parameters, how would I do this? Would it look like this?... cstmt = con.prepareCall("{?, ?, ?, ?, ?, ? = CALL MKTDS22B (?, ?, ?, ?, ?, ?)}"); or this?... cstmt = con.prepareCa

  • Sync new ipod to library

    How does one sync a new ipod to your current library?

  • Apex 2.2.1 vulnerabilities

    I had a quick question when researching apex. What are the current known vulnerabilities with 2.2.1? Are there any present SQL injection vulnerabilities, cross site scripting vulnerabilities? Also since 3.0 is out now, what are the main differences a