Digester: Extracting node name

前端 未结 2 1867
闹比i
闹比i 2021-01-23 22:24

Is it possible to extract the node name using apache digester?

So, if the xml looks like

   
     
       .....
              


        
2条回答
  •  不知归路
    2021-01-23 22:56

    (original answer)

    Create a Digester for pattern "furniture/*" with a simple Rule that takes the second parameter to each call to the begin method and sticks it in a collection of your choice (a list to get all of them, a set to get only all unique names).

    (edit)

    Scratch that, it's a bit more complicated.

    This works:

    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 match(String namespaceURI, String pattern) {
                    return Arrays.asList(printRule);
                }
            });
            dig.parse(instr);
        }
    }
    

    This particular sample will print all element names including the root furniture element. I'll leave it to you to adjust the match() method to your needs.

提交回复
热议问题