我有一个包含以下格式数据的表:
我需要进入以下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>
我正在尝试发现这样做的最佳实践方法。不幸的是,由于我被迫逐一阅读表格的行,所以我的手与流程捆绑在一起。
答案 0 :(得分: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);
}
}
请注意,代码需要反应才能更好看