2011-12-27 78 views
1

我有配置爲轉換器的xml文件。用Apache Commons配置讀取配置

<converter> 
    <replace> 
    <mask from="171, 187, 147, 148" to="34"/> 
    <mask from="150, 151" to="45"/> 
    </replace> 
</converter> 

要閱讀此配置,我使用Apache Commons Configuration。 我如何閱讀標籤「掩碼」迭代它,並在代碼中處理屬性?

回答

1

我的解決方案是使用xpath。

  XPath xpath = XPathFactory.newInstance().newXPath(); 
     XPathExpression fromAttribute = xpath.compile("@from"); 
     XPathExpression toAttribute = xpath.compile("@to"); 

     NodeList list = (NodeList) xpath.evaluate("/converter/replace/mask", 
        ((XMLConfiguration) configuration).getDocument(), XPathConstants.NODESET); 

     for (int i = 0; i < list.getLength(); i++) { 
      Node node = list.item(i); 
      String from = fromAttribute.evaluate(node); 
      String to = toAttribute.evaluate(node); 

      //... 
     }