这个问题在这里已经有答案了:
使用jaxb动态标记名(3个答案)
jax-b:从xmltattribute动态生成元素名(1个答案)
jaxb使用动态元素解组[重复](2个答案)
上个月关门了。
我需要按以下方式生成xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<document>
<attributeName1>
<value>abc</value>
<value>789</value>
</attributeName1>
<attributeName2>
<value>xyz</value>
<value>123</value>
</attributeName2>
<attributeName3>
<value>456</value>
</attributeName3>
</document>
attributename元素从java类变量value动态获取值。值是多值元素,可以包含一个或多个值。基本上是一个特定属性的值列表,例如:-attribute name-doc_name attribute value-list docvalue=new arraylist();
下面是我的document.java类
@XmlRootElement(name = "document")
public class XMLDocument implements Serializable {
private List<Attribute> attributes;
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
}
下面是我的attribute.java类
public class Attribute {
private String attributeName;
private List<String> attributeValueList;
/**
* @return the attributeName
*/
public String getAttributeName() {
return attributeName;
}
/**
* @param attributeName
* the attributeName to set
*/
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public List<String> getAttributeValueList() {
return attributeValueList;
}
@XmlElement(name="value")
public void setAttributeValueList(List<String> attributeValueList) {
this.attributeValueList = attributeValueList;
}
}
下面是我的testcreatingxml.java类
public class TestCreatingXml {
public static void main(String[] args) throws JAXBException {
List<Attribute> attrList = new ArrayList<>();
Attribute attr1 = new Attribute();
attr1.setAttributeName("attributeName1");
List<String> strValueList1 = new ArrayList<>();
strValueList1.add("abc");
strValueList1.add("789");
attr1.setAttributeValueList(strValueList1);
attrList.add(attr1);
Attribute attr2 = new Attribute();
attr2.setAttributeName("attributeName2");
List<String> strValueList2 = new ArrayList<>();
strValueList2.add("xyz");
strValueList2.add("123");
attr2.setAttributeValueList(strValueList2);
attrList.add(attr2);
Attribute attr3 = new Attribute();
attr3.setAttributeName("attributeName3");
List<String> strValueList3 = new ArrayList<>();
strValueList3.add("xyz");
strValueList3.add("123");
attr3.setAttributeValueList(strValueList3);
attrList.add(attr3);
XMLDocument xmlDocument = new XMLDocument();
xmlDocument.setAttributes(attrList);
JAXBContext jaxbContext = JAXBContext.newInstance(XMLDocument.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML
//Print XML String to Console
jaxbMarshaller.marshal(xmlDocument, new File("C:\\Users\\abc\\test.xml"));
}
}
我无法生成所需格式的xml。在这方面任何帮助都是非常感谢的。
暂无答案!
目前还没有任何答案,快来回答吧!