使用公共消化器如何将单个xml条目解析为对象中的多个字段?

时间:2009-11-06 20:30:19

标签: java apache-commons-digester

如何将“Joe Smith”映射到名字“Joe”姓氏“Smith”?

我已经有了拆分名称的代码,但我不知道如何使用Digester工作。

<guestlist>
  <guest>
   <name>Joe Smith</name>
  </guest>
</guestlist>

public class Guest(){
  private String firstName;
  private String lastName;
...
}

2 个答案:

答案 0 :(得分:1)

一个简单的答案是:为您的Guest类添加一个额外的属性:

public class Guest {
    private String firstName;
    private String lastName;
    public void setBothNames(String bothNames) {
        String[] split = bothNames.split(" ");
        firstName = split[0];
        lastName = split[1];
    }

和bean属性设置器规则到消化器:

    digester.addBeanPropertySetter("guestlist/guest/name", "bothNames");

答案 1 :(得分:0)

// Loading from a file, you can also load from a stream
XDocument loaded = XDocument.Load(@"C:\Guests.xml");


// Query the data and write out a subset of guests

var guests= from c in loaded.Descendants("guest")
        select new
        {
            FirstName = SplitFunc_FirstName(c.Element("name")),
            LastName = SplitFunc_LastName(c.Element("name"))
        };

foreach (var guest in guests)
{
    Your custom code...to attach it to your entity object.
}

注意:SplitFunc_FirstName是您已经编写的自定义函数,用于提取名字和姓氏。