-1

我有一个表格,其中包含以下格式的数据:

在此处输入图像描述

我需要进入以下 XML 格式:

<People>
     <Person>
          <FirstName>Mark</FirstName>
          <LastName>Smith</LastName>
          <PhoneNumbers>
               <PhoneNumber>
                    <Number>555-123-4567</Number>
                    <Type>Home</Type>
               </PhoneNumber>
               <PhoneNumber>
                    <Number>555-321-7654</Number>
                    <Type>Cell</Type>
               </PhoneNumber>
          <PhoneNumbers>
     <Person>
     <Person>
          <FirstName>Tim</FirstName>
          <LastName>Johnson</LastName>
          <PhoneNumbers>
               <PhoneNumber>
                    <Number>444-123-4567</Number>
                    <Type>Home</Type>
               </PhoneNumber>                   
          <PhoneNumbers>
     <Person>
     <Person>
          <FirstName>Larry</FirstName>
          <LastName>Walker</LastName>
          <PhoneNumbers>
               <PhoneNumber>
                    <Number>333-123-4567</Number>
                    <Type>Home</Type>
               </PhoneNumber>
               <PhoneNumber>
                    <Number>333-321-7654</Number>
                    <Type>Cell</Type>
               </PhoneNumber>
          <PhoneNumbers>
     <Person>

我正在尝试发现这样做的最佳实践方式。不幸的是,当我被迫一一阅读表格的行时,我的双手被束缚住了。

4

1 回答 1

1

您可以使用 JAXB。假设您知道如何解析您的表格:

@XmlRootElement(name="People")
@XmlAccessorType(XmlAccessType.FIELD)
class People {
    @XmlElement(name = "Person")
    private List<Person> persons = new ArrayList<Person>();

    public void addPerson(Person person) {
        persons.add(person);
    } 
}

@XmlAccessorType(XmlAccessType.FIELD)
class Person {
    String FirstName;
    List<PhoneNumber> PhoneNumber;
}

@XmlAccessorType(XmlAccessType.FIELD)
class PhoneNumber {
    String Number;
    String Type;
}

public class Test {

    public static void main(String args[]) throws Exception {
        PhoneNumber phoneNumber = new PhoneNumber();
        phoneNumber.Number = "555-555-555";
        phoneNumber.Type = "Home";

        Person person = new Person();
        person.FirstName = "Peter";
        person.PhoneNumber = Arrays.asList(phoneNumber, phoneNumber);

        People people = new People();
        people.addPerson(person);
        people.addPerson(person);

        StringWriter s = new StringWriter();
        JAXB.marshal(people, s);

        System.out.println(s);
    }
}

请注意,代码需要反应才能看起来更好

于 2012-11-21T04:13:16.347 回答