gpt4 book ai didi

html - HTML解析-从.html文件获取和更新数据

转载 作者:行者123 更新时间:2023-12-02 14:28:44 27 4
gpt4 key购买 nike

我在.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。该代码将以常规方式编写。有任何想法吗?

最佳答案

这似乎对我有用(经过反复试验)

@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 { it.@id == 'txtName' }

// Change it's value
i.@value = '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() )

[编辑]

得出以下结果:
<?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>

关于html - HTML解析-从.html文件获取和更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2510536/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com