1、定义表单,封装id,firstName和lastName
<form:form modelAttribute="person">
<form:hidden path="id" />
<fieldset>
<div class="form-row">
<label for="firstName"><fmt:message key="person.form.firstName"/>:</label>
<span class="input"><form:input path="firstName" /></span>
</div>
<div class="form-row">
<label for="lastName"><fmt:message key="person.form.lastName"/>:</label>
<span class="input"><form:input path="lastName" /></span>
</div>
<div class="form-buttons">
<div class="button">
<input type="submit" id="save" name="_eventId_save" value="<fmt:message key="button.save"/>"/>
<input type="submit" name="_eventId_cancel" value="Cancel"/>
</div>
</div>
</fieldset>
</form:form>
2、提交到servlet后,调用构造xml的java方法:
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance()
DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
// root elements
Document doc = docBuilder.newDocument()
Element rootElement = doc.createElement("company")
doc.appendChild(rootElement)
// staff elements
Element staff = doc.createElement("Staff")
rootElement.appendChild(staff)
// set attribute to staff element
Attr attr = doc.createAttribute("id")
attr.setValue("1")
staff.setAttributeNode(attr)
// shorten way
// staff.setAttribute("id", "1")
// firstname elements
Element firstname = doc.createElement("firstname")
firstname.appendChild(doc.createTextNode("yong"))
staff.appendChild(firstname)
// lastname elements
Element lastname = doc.createElement("lastname")
lastname.appendChild(doc.createTextNode("mook kim"))
staff.appendChild(lastname)
// nickname elements
Element nickname = doc.createElement("nickname")
nickname.appendChild(doc.createTextNode("mkyong"))
staff.appendChild(nickname)
// salary elements
Element salary = doc.createElement("salary")
salary.appendChild(doc.createTextNode("100000"))
staff.appendChild(salary)
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance()
Transformer transformer = transformerFactory.newTransformer()
DOMSource source = new DOMSource(doc)
StreamResult result = new StreamResult(new File("d:\\person.xml"));
transformer.transform(source, result)
System.out.println("File saved!")
} catch (ParserConfigurationException pce) {
pce.printStackTrace()
} catch (TransformerException tfe) {
tfe.printStackTrace()
}
3、构造完成:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<company>
<staff id="1">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
</company>
html本身也是xml的,两者可以来回转换的,建议你去找一些xslt的资料看看。xslt是.NET里面专门用来转换xml的一个类。
当然前提是你对.NET *** 作XML非常熟悉
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)