Apache XML Configuration get node by attribute

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    Apache XML Configuration get node by attribute

    Hey guys,

    Couldn't find what I'm looking for, so trying to see if anybody has worked with Apache Commons XML Configuration.

    I can read attributes and nodes by name just fine, what I was looking for was a look-up function by ID.

    SO

    Code:
    <nodes>
      <node id="123" foo="bar1">test1</node>
      <node id="456" foo="bar2">test2</node>
    </nodes>
    If you have a String str = "456", how do you make XMLConfiguratio n class give you the second node in this example without getting all the id's and looping through it (which is what I'm currently doing).

    Desired Code:
    Code:
    String str = "456"; 
    XMLConfiguration config = new XMLConfiguration("config.xml"); 
    config.setExpressEngine(new XPathExpressionEngine()); 
    
    HierarchicalConfiguration node = (HierarchicalConfiguration) config.getNodeByID(str);
    
    String foo = node.getString("[@foo]"); 
    
    System.out.println(foo); 
    
    /**
    Ouputs: 
    bar2
    */
    Thanks!


    Dan
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    The Answer: You already are using XPATH, just call an equals expression:

    Code:
    # String str = "456"; 
    # XMLConfiguration config = new XMLConfiguration("config.xml"); 
    # config.setExpressEngine(new XPathExpressionEngine()); 
    #  
    # HierarchicalConfiguration node = (HierarchicalConfiguration) config.configurationAt("/nodes/node[@id='"+(str)+"']"); // <-- CASE SENSITIVE I THINK
    #  
    # String foo = node.getString("@foo"); // <-- Remove brackets []
    #  
    # System.out.println(foo); // VOILA!!
    Hope that helps anyone else with the same issue,


    Dan

    Comment

    Working...