0

我正在尝试从 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”,但它们并没有成功。

4

1 回答 1

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");
}
于 2013-12-03T08:29:08.347 回答