1

I have a form in a .html files where input/select box looks like this

<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>

I would need to remove '##' value textbox and also update them with different values if needed be in the textbox/checkbox/ selectbox. I would know the id of the input types. The code is to be written in groovy. Any ideas?

3 Answers 3

1

This seems to work for me (took a bit of trial and error)

@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() )

[edit]

That gives this result:

<?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>
Sign up to request clarification or add additional context in comments.

Comments

1

Groovy's XmlParser supports reading and updating of XML documents.

Comments

1

I would suggest you to use the builtin groovy builder. It can work also with a custom SAX parser like TagSoup.

You can easily do things like

tbl.tr.list().each { row ->

}

as described here..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.