java中xml设置多个属性_Java HTML/XML - 如何如果设置了另一个可选属性,请设置可选属性...

import javax.xml.bind.JAXBContext;

import javax.xml.bind.Marshaller;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlAttribute;

import javax.xml.bind.annotation.XmlRootElement;

public class Main {

public static void main(String[] args) throws Exception {

JAXBContext jc = JAXBContext.newInstance(Field.class);

Marshaller marshaller = jc.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

Field field = new Field();

field.name = "myField";

marshaller.marshal(field, System.out);

field.status = "citizen";

field.country = "England";

marshaller.marshal(field, System.out);

field.status = null;

marshaller.marshal(field, System.out);

}

@XmlRootElement

@XmlAccessorType(XmlAccessType.FIELD)

public static class Field {

@XmlAttribute

String name;

@XmlAttribute

String status;

@XmlAttribute

String country;

private void beforeMarshal(Marshaller marshaller) {

if (country != null && status == null) {

throw new RuntimeException("country was set but status was not");

}

}

}

}


版权声明:本文为weixin_34708196原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。