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