开发者

Digester: Extracting node name

开发者 https://www.devze.com 2022-12-18 07:42 出处:网络
Is开发者_如何学编程 it possible to extract the node name using apache digester? So, if the xml looks like

Is开发者_如何学编程 it possible to extract the node name using apache digester?

So, if the xml looks like

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

is it possible to extract the node name "sofa", "coffeeTable"?

I know it is possible using xpath but is it possible using digester?

Cheers


(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<Rule> 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.


This is the kind of matching that ExtendedBaseRules afford.

Let's say this is the content of furniture.xml:

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

Let's say you want to get the element names of the direct children of furniture element. This is what furniture/? matches in the ExtendedBaseRules.

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 links

  • Package org.apache.commons.digester
  • org.apache.commons.digester.Rule
  • org.apache.commons.digester.ExtendedBaseRules
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号