如何使用Apache Commons Digester忽略命名空间?

时间:2013-12-03 08:29:08

标签: xml-namespaces google-contacts apache-commons-digester

我正在尝试解析Google Contacts API中的XML。与我和这个问题相关的部分是给定的姓名,姓氏和电子邮件地址,它们看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005">
<entry>
  <gd:name>
    <gd:fullName>John Doe</gd:fullName>
    <gd:givenName>John</gd:givenName>
    <gd:familyName>Doe</gd:familyName>
  </gd:name>
  <gd:email rel="http://schemas.google.com/g/2005#work" address="john.doe@example.org" primary="true"/>
</entry>
<entry>
  <gd:name>
    <gd:fullName>Jane Smith</gd:fullName>
    <gd:givenName>Jane</gd:givenName>
    <gd:familyName>Smith</gd:familyName>
  </gd:name>
  <gd:email rel="http://schemas.google.com/g/2005#work" address="jane.smith@foo.bar" primary="true"/>
</entry>
</feed>

我的消化器类看起来像这样:

public class GmailContactsDigester {
  private Digester digester;

  public GmailContactsDigester() {
    digester = new Digester();
    digester.addObjectCreate("feed", ArrayList.class);
    digester.addObjectCreate("feed/entry", GoogleContact.class);
    digester.addBeanPropertySetter("feed/entry/gd:name/gd:givenName", "givenName");
    digester.addBeanPropertySetter("feed/entry/gd:name/gd:familyName", "familyName");
    digester.addRule("feed/entry/gd:email/", new SetPropertiesRule("address", "email"));
    digester.addSetNext("feed/entry", "add");
  }

  public List<GoogleContact> parse(InputStream xmlStream) {
    try {
      return (List<GoogleContact>) digester.parse(xmlStream);
    } catch (IOException e) {
      throw new RuntimeException(e);
    } catch (SAXException e) {
      throw new RuntimeException(e);
    }
  }
}

并且GoogleContact类只是我的小域对象,包含必需的字段和设置器。

这一切都很好,但依赖于XML中使用的名称空间前缀。无论命名空间如何,我都希望它能够工作,只需要元素本地名称。我怎么做?我已经为bean属性设置器中的模式尝试了各种语法,比如“feed / entry / *:email”和“feed / entry / email”,但是他们没有做到这一点。

1 个答案:

答案 0 :(得分:1)

解决方案是让Digester命名空间知道,并使规则匹配忽略命名空间:

public GmailContactsDigester() {
  digester = new Digester();
  digester.setRuleNamespaceURI(null);
  digester.setNamespaceAware(true);
  digester.addObjectCreate("feed", ArrayList.class);
  digester.addObjectCreate("feed/entry", GoogleContact.class);
  digester.addBeanPropertySetter("feed/entry/name/givenName");
  digester.addBeanPropertySetter("feed/entry/name/familyName");
  digester.addRule("feed/entry/email/", new SetPropertiesRule("address", "email"));
  digester.addSetNext("feed/entry", "add");
}