HTML解析 - 从.html文件
问题描述:
我有一个.html文件形式,其中输入/选择框看起来像这样HTML解析 - 从.html文件
<input type="text" id="txtName" name="txtName" value="##myName##" />
<select id="cbGender" name="cbGender">
<option>Select</option>
<option selected="selected">Male</option>
<option>Female</option>
</select>
我需要删除“##”值文本框获取和更新数据并根据需要在文本框/复选框/选择框中使用不同的值更新它们。我会知道输入类型的ID。代码是用groovy编写的。有任何想法吗?
答
这似乎为我工作(采取了一些试验和错误的)
@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='1.2')
import org.ccil.cowan.tagsoup.*
import groovy.xml.*
String htmlTxt = """<html>
<body>
<input type="text" id="txtName" name="txtName" value="##myName##" />
<select id="cbGender" name="cbGender">
<option>Select</option>
<option selected="selected">Male</option>
<option>Female</option>
</select>
</body>
</html>"""
// Define our TagSoup backed parser
def slurper = new XmlSlurper(new Parser())
// Parse our html
def h = slurper.parseText(htmlTxt)
// Find the input with the id 'txtName'
def i = h.body.input.list().find { [email protected] == 'txtName' }
// Change it's value
[email protected] = 'new value'
// Write it out (into a StringWriter for now)
def w = new StringWriter()
w << new StreamingMarkupBuilder().bind {
// Required to avoid the html: namespace on every node
mkp.declareNamespace '':'http://www.w3.org/1999/xhtml'
mkp.yield h
}
// XmlUtil.serialize neatens up our resultant xml -- but adds an xml declaration :-(
println new XmlUtil().serialize(w.toString())
[编辑]
那g ives结果:
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<input id="txtName" name="txtName" value="new value" type="text"/>
<select id="cbGender" name="cbGender">
<option>Select</option>
<option selected="selected">Male</option>
<option>Female</option>
</select>
</body>
</html>
答
Groovy的XmlParser支持读取和更新XML文档。
非常感谢它的工作。 – 2010-03-25 05:11:33