代码之家  ›  专栏  ›  技术社区  ›  CaptainHastings

消化器:提取节点名称

  •  1
  • CaptainHastings  · 技术社区  · 15 年前

    是否可以使用apache消化器提取节点名?

    因此,如果XML看起来像

       <furniture>
         <sofa>
           .....
         </sofa>
         <coffeeTable>
           .....
         </coffeeTable>
       </furniture>
    

    是否可以提取节点名“sofa”、“coffeetable”?

    我知道使用xpath是可能的,但是使用消化器是可能的吗?

    干杯

    2 回复  |  直到 15 年前
        1
  •  1
  •   Barend    15 年前

    (原始答案)

    创建一个 Digester 为模式 "furniture/*" 用一个简单的 Rule 它将第二个参数带到每个对begin方法的调用中,并将其粘贴到您选择的集合中(一个获取所有参数的列表,一个仅获取所有唯一名称的集合)。

    (编辑)

    刮掉它,就更复杂了。

    这工作:

    public class App 
    {
        final static Rule printRule = new Rule() {
            public void begin(String namespace, String name,
                    Attributes attributes) throws Exception {
                System.out.println(name);
            }
        }; 
        public static void main( String[] args ) throws IOException, SAXException
        {
            InputStream instr = App.class.getResourceAsStream("/sample.xml");
            Digester dig = new Digester();
            dig.setRules(new RulesBase(){
                public List<Rule> match(String namespaceURI, String pattern) {
                    return Arrays.asList(printRule);
                }
            });
            dig.parse(instr);
        }
    }
    

    此特定示例将打印所有元素名,包括根 furniture 元素。我把它留给你来调整 match() 方法满足您的需要。

        2
  •  0
  •   polygenelubricants    15 年前

    这是那种匹配的 ExtendedBaseRules 负担得起。

    假设这是 furniture.xml :

    <furniture>
       <sofa>
          <blah/>
       </sofa>
       <coffeeTable>
          <bleh/>
       </coffeeTable>
    </furniture>
    

    假设您要获取 furniture 元素。这是什么 furniture/? 比赛中 扩展的基本规则 .

    import java.io.*;
    import java.util.*;
    import org.apache.commons.digester.*;
    
    public class FurnitureDigest {
        public static void main(String[] args) throws Exception {
            File file = new File("furniture.xml");
            Digester digester = new Digester();
            digester.setRules(new ExtendedBaseRules());
            final List<String> furnitures = new ArrayList<String>();
            digester.addRule("furniture/?", new Rule() {
                @Override public void end(String nspace, String name) {
                    furnitures.add(name);
                }
            });
            digester.parse(file);
            System.out.println(furnitures); // prints "[sofa, coffeeTable]"
        }
    }
    

    API链接

    推荐文章