JSP如何将HTML的表单数据提交生成一个XML文件

JSP如何将HTML的表单数据提交生成一个XML文件,第1张

JSP将HTML的表单数据提交生成一个XML文件的方法:

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非常熟悉


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/7183804.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-02
下一篇 2023-04-02

发表评论

登录后才能评论

评论列表(0条)

保存