在沼气池中解析地图

时间:2012-02-15 11:02:20

标签: java xml apache-commons-digester

我有一串XML

<ShowPercentage>     
    <SPGLevel>       
        <Level> 1 </Level>   
        <percentage>40</percentage>      
    </SPGLevel>
    <SPGLevel>       
        <Level> 2 </Level>
        <percentage>60</percentage>      
    </SPGLevel>
</ShowPercentage>

SPG级别是可重复的。这是一个key = Level和value = percentage

的地图

我想使用Digester解析这个XML。任何人都可以帮助我开始吗?

5 个答案:

答案 0 :(得分:3)

答案可能类似于以下代码,但我没有测试

public class SampleDigester
{
  private Map<String, String> map = new HashMap<String, String>();

  public void run() throws IOException, SAXException {    
    Digester digester = new Digester();
    digester.push(this);

    digester.addCallMethod("ShowPercentage/SPGLevel", "addKey", 2);
    digester.addCallParam("ShowPercentage/SPGLevel/Level", 0);
    digester.addCallParam("ShowPercentage/SPGLevel/percentage", 1);
    digester.parse("input.xml");

  }

  public void addKey(String key, String value) {
    map.put(key, value);
  }

}

答案 1 :(得分:1)

digester.addObjectCreate("MerchRecomExitPopupControl/ShowPercentage", HashMap.class);
digester.addCallMethod("MerchRecomExitPopupControl/ShowPercentage/SPGLevel", "put", 2);
digester.addCallParam("MerchRecomExitPopupControl/ShowPercentage/SPGLevel/Level", 0);
digester.addCallParam("MerchRecomExitPopupControl/ShowPercentage/SPGLevel/Percentage", 1);
digester.addSetNext("MerchRecomExitPopupControl/ShowPercentage", "setShowPercentMap");

setShowPercentMap - 在辅助类中设置它,字符串映射

答案 2 :(得分:1)

    final String root= "root/";
    final String out= "elementOut/";
    final String in= "elementIn/";
    final String id = "id";
    final String NAME = "name";

    String namespace = reg.getFilename();
    final Digester digester = new Digester();
    digester.setValidating(false);

    digester.addObjectCreate(root, HashMap.class);
    digester.addCallMethod(root+ out, "put", 2);
    digester.addCallParam(root+ out, 0, ID);
    digester.addObjectCreate(root+ out, ArrayList.class);
    digester.addCallMethod(root+ out + in, "add", 1);
    digester.addCallParam(root+ out + in, 0, name);
    digester.addCallParam(root+ out, 1, true);
    Map<String, List<String>> map = digester.<Map<String, List<String>>> parse(reg
                .getInputStream());

对应的xml将key的映射与字符串匹配,将值作为字符串列表匹配。

 <root>
    <elementOut id="key1">
   <elementIn name="value1" />
       </elementOut>
   <elementOutid="key2">
   <elementIn name="value1" />
   <elementIn name="value2" />
   </elementOut>
</root>

答案 3 :(得分:0)

我应该建议您使用脚轮映射。

Castor mapping

对于Castor映射,您应该按照以下步骤操作:

  1. 编写您的xml文件。
  2. 根据您的xml文件制作mapping.xml文件。
  3. 根据您的主xml文件制作Pojo。
  4. 完成所有内容后,请记下以下代码进行解组。

    private String fileLoadPath="conf/Configuration.xml";
    private String mappingPath="conf/mapping.xml";
    
     Mapping mapping = new Mapping();
     mapping.loadMapping(mappingPath);
    
    Configuration configuration = (Configuration)new Unmarshaller(mapping).unmarshal(fileLoadPath);
    

答案 4 :(得分:-1)