我有一个用于使用 JAXB 创建 XML 文件的 java 代码,我知道如何创建根元素和元素,但我想从这样的元素创建一个子元素:
<root element>
<element>
<child element>
<group of elements and attributes>
</child element>
</element>
</root element>
我现在只知道如何创建这样的:
<XmlSource URL="http://local.yahoo.com/rss/restaurants?csz=Cairo,+CA">
<hostName>local.yahoo.com</hostName>
<parameters>
<entry>
<key>csz</key>
<value>Cairo,+CA</value>
</entry>
</parameters>
<urlPath>/rss/restaurants</urlPath>
</XmlSource>
那么,如果我想将参数放在 hostName 中,我会怎么做:
<XmlSource URL="http://local.yahoo.com/rss/restaurants?csz=Cairo,+CA">
<hostName name="local.yahoo.com">
<parameters>
<entry>
<key>csz</key>
<value>LosAngelos,+CA</value>
</entry>
</parameters>
</hostName>
<urlPath>/rss/restaurants</urlPath>
</XmlSource>
最后是我使用的java代码:
我把注释放在的类:
@XmlRootElement(name= "Source")
public class XmlConf {
@XmlElement(name= "Source")
private URL url;
private List<String> path = new ArrayList<String>();
private String urlp;
private Map<String, String> parameters;
private String host;
public URL getUrl() {
return url;
}
@XmlAttribute(name = "URL")
public void setUrl(URL url) {
this.url = url;
}
@XmlElement
public List<String> getPath() {
return path;
}
public void setPath(String path) {
this.path.add(path);
}
@XmlElement
public void setUrlPath(String urlp){
this.urlp = urlp;
}
public String getUrlPath(){
return urlp;
}
@XmlElement(name = "param")
public void setParameters(Map<String, String> parameters){
this.parameters = parameters;
}
public Map<String, String> getParameters(){
return parameters;
}
public void setHostName(String host){
this.host = host;
}
public String getHostName(){
return host;
}
}
我使用 JAXB 的课程:
public class ConfList {
private static final String fileName = "Source.xml";
List<String> xmlConfList;
private Object object;
public ConfList(Object object){
this.object = object;
}
public void addToList() throws IOException, JAXBException {
File file = new File(object+fileName);
JAXBContext jaxbContext = JAXBContext.newInstance(XmlConf.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(object, file);
jaxbMarshaller.marshal(object, System.out);
}
}