XPath - How to get only second matching node?

Hello,
withs this XPath expression:
//td[contains(@name, 'FirstColumn')]on this XML:
<html>
     <table>
          <tr>
               <td name="MyFirstColumnInRow">A11 - skip me!</td>
               <td name="MySecondColumnInRow">A12</td>
          </tr>
          <tr>
               <td name="MyFirstColumnInRow">A21 - find me!</td>
               <td name="MySecondColumnInRow">A22</td>
          </tr>
          <tr>
               <td name="MyFirstColumnInRow">A31 - skip me!</td>
               <td name="MySecondColumnInRow">A32</td>
          </tr>
     </table>
</html>I have got three matching nodes: A11, A21, A31 .
How to expand this XPath expression to get only the second node: A21 ?
I can't find appropriate solution.
Thanks in advance.

Why don't you get all the nodes and than you can do whatever you want? You can even get an iterator (here commented out) or write your rule in a loop.
    public static Document parseXmlIntoDOM(File xmlFile,boolean validating,boolean spaceAware) throws XMLException{
        Document document = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(validating);  
        factory.setNamespaceAware(spaceAware);
        try {
           DocumentBuilder builder = factory.newDocumentBuilder();
           document = builder.parse(xmlFile);
        catch (SAXException sxe) {throw new XMLException("An error in parsing the input source",sxe);}
        catch (ParserConfigurationException pce) {throw new XMLException("An error in parsing the input source",pce);}
        catch (IOException ioe) {throw new XMLException("An error in parsing the input source",ioe);}
        return document;
    public static void main(String args[]){
        Document dom;
        try{
            File file = new File("C:\\Documents and Settings\\diego\\xml\\newXMLDocument.xml");       
            dom = parseXmlIntoDOM(file,false,true);
            XPath xpath = XPathFactory.newInstance().newXPath();
            String expression = "/html/table/tr/td";
            DTMNodeList tdNodes = (DTMNodeList)xpath.evaluate(expression, dom, XPathConstants.NODESET);
            //DTMIterator iterator=tdNodes.getDTMIterator();
            Node secondinstance = tdNodes.item(2);
            System.out.println(secondinstance.getTextContent());
            }catch(Exception e){
                e.printStackTrace();
    }This works just fine for me and that is my output (in the standard):
compile:
run:
A21 - find me!
BUILD SUCCESSFUL (total time: 1 second)Sorry the code I wrote is awful, but working. P.S. is there a way for not using the "DTM" api?

Similar Messages

  • How to get only seconds from the time block function?

    Hello, I want to know to get only "seconds" from the time function. I tried to find other time function but I couldn't find anything that provides only second to be written in the text file.

    It may not be the best way but it works...
    Rodéric L
    Certified LabVIEW Architect

  • How to get only direct child node by tag name

    Hi,
    I am using the method
    getElementsByTagName("")....
    This works except the problem is my XML schema/file has some recursive tags,
    I have a <question> element which can have an <answer> or another <question>.
    When parsing the XML file I want to be able to get a list of sub questions for a given question, but only if it is a direct child of that question.
    So if i have:
    <question>
      <text>q1</text>
      <question>
        <text>q2</text>
        <question>
          <text>q3</text>
        </question>
      </question>
    </question>If I'm dealing with the "q1" question I want only "q2" but not "q3". Whereas getElementsByTagName will take both q2 and q3. How can I achieve this.
    Thanks

    You want only children and not other descendants? Then getChildNodes() and getFirstChild() and methods with similar names look like a good start.

  • How to get only expanded node after open & close in CL_GUI_ALV_TREE?

    Hi,
    I have a tree structure using CL_GUI_ALV_TREE.
    I would like to capture only the expanded nodes AFTER open and close operation.
    If the user opens all the nodes and then closes them, I get all the nodes when using GET_EXPANDED_NODES.
    I want to get only the expanded nodes that the user currently sees on the screen (so in open and close you will not get it as open).
    whatever I tried doesn't work.
    Do you have any idea how to do it?
    Thanks,
    Itay

    this methods calls method of attribute MR_COLUMN_TREE without setting the parameter NO_HIDDEN_NODES to 'X'
    that's why you get every node that is "open" even if not "visible"
    as this attribute MR_COLUMN_TREE is protected, you cannot access it...
    you should consider using an object of class CL_GUI_COLUMN_TREE directly in place of CL_GUI_ALV_TREE so that you can call the method with this parameter set...
    you will have far more to do by hand but you will get more flexibility...

  • How to get the following-sibling nodes until a specific node

    XSL people,
    I need to get all the following-sibling nodes for every <h> node until the next <h> node.
    Example:
    <body>
    <h>Header1</h>
    <a>Line 11</a>
    <b>Line 12</b>
    <c>Line 13</c>
    <a>Line 14</a>
    <h>Header2</h>
    <a>Line 21</a>
    <c>Line 22</c>
    <a>Line 23</a>
    <b>Line 24</b>
    </body>
    So I need to get this strings:
    from the first <h> node: Line 11Line 12Line 13Line 14
    from the second <h> node: Line 21Line 22Line 23
    When using following-sibling
    <xsl:value-of select="following-sibling::a"/>
    <xsl:value-of select="following-sibling::b"/>
    <xsl:value-of select="following-sibling::c"/>
    I am not getting the second <a> node (of course!), so for the first <h> node I am only getting
    Line 11Line 12Line 13
    and not
    Line 11Line 12Line 13Line 14
    and I don't know how to get it.
    Thank you.
    Anatoliy Smirnov

    Thanks Sudipto for trying to help. I did try that, and as I mentioned in the previous posting, it doesn't work for the tree nodes (multiple RowSetIterator). the following is my code, where the treeVO is the vo instance for the firstLevel tree nodes and it has view link to its children. I am not sure how to sort all children for each level. Even for the first level where I did the explicit sorting in memory, it still not sorting at all.
    treeVO.setSortBy("code");
    treeVO.setQueryMode(ViewObject.QUERY_MODE_SCAN_ENTITY_ROWS|ViewObject..QUERY_MODE_SCAN_DATABASE_TABLES);
    treeVO.executeQuery();

  • How to get a second page in a form letter report after create it by Wizard

    How to get a second page in a form letter report after create it by Wizard
    i've built a report by wizard with a sql-Query
    the sql give me back for example 3 dataset
    and the report prints 3 pages
    dataset 1 - page 1
    dataset 2 - page 1
    dataset 3 - page 1
    thats ok,
    but now I need a second page per dataset ( with only a text )
    so that the report should print 2 pages per dataset
    dataset 1 - page 1 ,page 2
    dataset 2 - page 1 ,page 2
    dataset 3 - page 1 ,page 2
    It's not really clear for me, what to do, to create the second page
    any help ?

    .... found answer in other forum

  • XML parsing - NodeList : how to get only the desired childs

    Hi
    my question is about parsing XML files. I use "getChildNodes()" method (from org.w3c.dom.Node class) to get in a NodeList all childs of node. Is there a method to get only desired child nodes? For example I want to get only node elements wtih tag "coordinate". Or alternatively, is there a method to exclude text node to be added to the NodeList? My problem is that depending on the xml is formatted, text node could be recognized and added from parser, and this causes problems with my parsing..
    thanks to all

    If you want to select nodes based on changing criteria, you should use XPath.
    If you have relatively fixed criteria, iterate over the nodes and pick out the ones that you want. For example:
      public static List<Element> getChildren(Element parent, String tagname) {
        List<Element> result = new ArrayList<Element>();
        NodeList children = parent.getChildNodes();
        for (int ii = 0 ; ii < children.getLength() ; ii++) {
          Node child = children.item(ii);
          if ((child.getNodeType() == Node.ELEMENT_NODE) && tagname.equals(child.getNodeName()) {
            result.add((Element)child);
        return result;
      }

  • How to get only the first result in extract function

    do you know how to get only the first element of the function extract.
    v_result := p_response.doc.extract('//'||p_name||'/child::text()').getstringval();
    if i have 5 responses like '100','100',100','200','200' e get '100100100200200' and i want only '100'.
    thanks in advance

    Two ways .....
    1. Use Javascript E4X instead ...there are nice functions for getting children of parents.
    2. Cycle through all of the form1.nodes and look for objects that have a className of "subform". For loops are useful for this task.
    Make sense?
    Paul

  • In Table Control How to get only a single row .

    Hi
    In Table Control How to get only a single row .I am able to decrease it its height to 4 but then 2 rows is getting dsplayed .I want only one row to be display and 2nd row should be deactivated or not visible.
    regards
    Avik
    Edited by: Julius Bussche on Jan 30, 2009 1:10 PM
    Removed friendly greeting from the subject title

    Hi Avik
    use this code it will help you.
    MODULE passdata OUTPUT.
      READ TABLE it_revision INTO wa_rev INDEX tab_clc-current_line.
      IF sy-subrc = 0.
        LOOP AT SCREEN.
          IF screen-group1 = '111'.      " 111 IS THE GROUP NAME
            screen-input = 1.          " input mode
            screen-active = 1.         " input mode.
            MODIFY SCREEN.
          ENDIF.
        ENDLOOP.
      ELSE.
        LOOP AT SCREEN.
          IF screen-group1 = '111'.       "GROUP NAME
            screen-input = 0.           " display mode
            screen-active = 1.          " DISPLAY MODE.
            MODIFY SCREEN.
          ENDIF.
        ENDLOOP.
      ENDIF.
    ENDMODULE.                 " PASSDATA  OUTPUT
    Make sure in group tou are passing the field name that you want in input mode on the base of other field
    Hope it will help you.
    Thanks
    Arun Kayal.

  • How to get only current exception message from tables

    Hi
    In my sceanario , I want to have the list of Current MRP exception messages list from table
    I understand that MRP detailed lists, including all exception messages, are stored in transparent table MDKP and cluster table MDTC.
    I can tell ABAPer to write a report for me , to read the data from these tables , but I guess these tables contain old exception message also , which are not currently appearing in MRP list
    How to get only current exception message
    Rgds,
    sandeep

    Sandeep,
    MDTC contains only data from the most recent MRP run.  So, all messages you see are those which are currently valid.
    The messages might have first appeared during a previous run, but they still need to be addressed.
    Before you invest a lot of time and effort into writing and debugging a custom report, you should probably try to use the standard SAP functionality found in MD06.  On the Processing indicator tab, you can select "Only with new exceptions".  Here you can tag a material/plant as 'processed', and thereafter, the exceptions that existed there before you tagged the part will not be re-displayed.
    Best Regards,
    DB49

  • How to get Value of tree node without Reload Page

    hi,
    i worked with apex 4.2 and i created Tree and tabular form to retrieve the date according the value of tree select node the code of tree something like this
    select case when connect_by_isleaf = 1 then 0
    when level = 1 then 1
    else -1
    end as status,
    level,
    "ENAME" as title,
    null as icon,
    "EMPNO" as value,
    null as tooltip,
    'f?p=36648:34:5234984107903::::P40_SELECTED_NODE:'||empno as link
    from "DEPT"."EMP"
    start with "MGR" is null
    connect by prior "EMPNO" = "MGR"
    order siblings by "ENAME
    and i put Selected Node Page Item: P40_SELECTED_NODE . the tree worked good and retrieve the data into tabular form according to tree node value
    my Question :
    1- i want to retrieve the data without submit the page where each time i select value from tree make page reload to update the tabular form with new value ,there is any way to pass the value of tree node to P40_SELECTED_NODE item and refresh tabular form without page reload .
    2- i want when selected from tree run page process according to value of tree node i tray to create Dynamic action with *(jquery selector : div.tree li>a)* but the Value of node incorrect.
    Regards
    Ahmed;

    look at this link
    Re: How to get Value of tree node without Reload Page ..!

  • How to get only the first level of nodes for a subform?

    How can we get only the first level of nodes of a subform?
    For ex:
    Form1
         SubForm1
              Text1
              Text2
              RadioButton1
         SubForm2
              Text1
              Text2
              RadioButton1
         SubForm3
              Text1
              Text2
                   SubForm31
                        RadioButton1
    In this heirarchy if we give Form1.nodes will refer to all nodes under the Form1 (SubForm1,Test1,Text2,RadioButton1,SubForm2,...SubForm31, RadioButton1 etc..)
    But is there any way that we can access only the first level of nodes of Form1 ie can we get only (SubForm1,SubForm2,SubForm3) for Form1 in any Way..?
    Thanks.

    Two ways .....
    1. Use Javascript E4X instead ...there are nice functions for getting children of parents.
    2. Cycle through all of the form1.nodes and look for objects that have a className of "subform". For loops are useful for this task.
    Make sense?
    Paul

  • How to get only matching rows in Full Outer Join

    HI All,
    I was recently asked this question.
    How to fetch only matching data from two tables using Full Outer Join. Now, I understand that this is not the objective of using Full Joins but I was wondering whether this is possible or not.
    Any help in this regard will be highly appreciated.

    Full outer join returns both matching and not matching rows, if you want only matching rows why you don't use INNER JOIN?
    The following query does an INNER JOIN using a FULL JOIN which I think it doesn't make any sense.
    SELECT *
    FROM
    A FULL OUTER JOIN B
    ON A.ColumnName = B.ColumnName
    WHERE
    A.ColumnName IS NOT NULL
    AND B.ColumnName IS NOT NULL
    EntityLite: A Lightweight, Database First, Micro ORM

  • How-to get path to a node in SPRO

    Hello guys,
    I'm working on a tool which creates automatic dcumentation tool of changes in SPRO. All goes fine except one thing:
    I need to generate a PATH to IMG ACTIVITY. I know the code of activity, I know it's HIER_GUID. What I need to get is all "parents" HIER_GUID of bottom node.
    So far I got only one FM - STREE_GET_PATH_TO_NODE. It's fine but it returns only the path to 03 level in SPRO. (01 - is top, 02 - are components).
    What I desperatly need is how to get a connection from 03 to 02 level.
    You can simulate the FM with following values:
    SEARCH_FOR_NODE-NODE_ID = 1C1B49FEC279D411AB74009027B70B8E
    SEARCH_FOR_NODE-TREE_ID = 367A8DF9ACEE16E7E10000009B38F976
    The result contain the highest node id 367A8DAFACEE16E7E10000009B38F976, which stands for "SAP Business Parnter" (according the table TNODEIMGT-NODE_ID).
    But the fact, that "SAP Business Partner" is in "Cross-Application Components" is unreachable for me.
    Do you know, how to get relevant node on level 02 ?
    All hints will be rewarded.
    Thank you
    Regards
    Tomas

    Hello guys,
    I'm working on a tool which creates automatic dcumentation tool of changes in SPRO. All goes fine except one thing:
    I need to generate a PATH to IMG ACTIVITY. I know the code of activity, I know it's HIER_GUID. What I need to get is all "parents" HIER_GUID of bottom node.
    So far I got only one FM - STREE_GET_PATH_TO_NODE. It's fine but it returns only the path to 03 level in SPRO. (01 - is top, 02 - are components).
    What I desperatly need is how to get a connection from 03 to 02 level.
    You can simulate the FM with following values:
    SEARCH_FOR_NODE-NODE_ID = 1C1B49FEC279D411AB74009027B70B8E
    SEARCH_FOR_NODE-TREE_ID = 367A8DF9ACEE16E7E10000009B38F976
    The result contain the highest node id 367A8DAFACEE16E7E10000009B38F976, which stands for "SAP Business Parnter" (according the table TNODEIMGT-NODE_ID).
    But the fact, that "SAP Business Partner" is in "Cross-Application Components" is unreachable for me.
    Do you know, how to get relevant node on level 02 ?
    All hints will be rewarded.
    Thank you
    Regards
    Tomas

  • How to get total number of nodes in a JTree?

    Hi,
    I am trying to get total number of nodes in a JTree, and cannot find a way to do it.
    The current getRowCount() method returns the number of rows that are currently being displayed.
    Is there a way to do this or I am missing something?
    thanks,

    How many nodes does this tree have?
    import java.awt.EventQueue;
    import javax.swing.*;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.*;
    public class BigTree {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    TreeModel model = new TreeModel() {
                        private String node = "Node!";
                        @Override
                        public void valueForPathChanged(TreePath path,
                                Object newValue) {
                            // not mutable
                        @Override
                        public void removeTreeModelListener(TreeModelListener l) {
                            // not mutable
                        @Override
                        public boolean isLeaf(Object node) {
                            return false;
                        @Override
                        public Object getRoot() {
                            return node;
                        @Override
                        public int getIndexOfChild(Object parent, Object child) {
                            return child == node ? 0 : -1;
                        @Override
                        public int getChildCount(Object parent) {
                            return 1;
                        @Override
                        public Object getChild(Object parent, int index) {
                            return node;
                        @Override
                        public void addTreeModelListener(TreeModelListener l) {
                            // not mutable
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(new JScrollPane(new JTree(model)));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }But for bounded tree model using DefaultMutableTreeNode look at bread/depth/preorder enumeration methods to walk the entire tree. Or look at the source code for those and adapt them to work with the TreeModel interface.

Maybe you are looking for