1

I am using groovy, so an java implementation would also be fine.

I have

"""<TextFlow fontFamily="Arial" fontSize="20"><span>before</span>Less than 7 days<span>after</span></TextFlow>"""

I would like to wrap first level text node with a tag. So I would like to get

"""<TextFlow fontFamily="Arial" fontSize="20"><span>before</span><span>Less than 7 days</span><span>after</span></TextFlow>"""

I have looked into XmlSlurper which doesn't deal with text nodes. I have also looked into XmlParser which can handle text nodes, but I am not sure how to replace it with an xml element. Please advice.

1 Answer 1

1

This worked for me, hope it'd help someone else

@Grab('org.jdom:jdom2:2.0.5')
@Grab('jaxen:jaxen:1.1.4')
@GrabExclude('jdom:jdom')

import org.jdom2.*
import org.jdom2.input.*
import org.jdom2.xpath.*
import org.jdom2.output.*

def xml = """<TextFlow fontFamily="Arial" fontSize="20"><span>before</span>Less than 7 days<span>after</span></TextFlow>"""

Document doc = new SAXBuilder().build(new StringReader(xml)) 
def urls = XPathFactory.instance().compile('//TextFlow/text()').evaluate(doc)

for(def c in urls) {
    int pos = c.parent.content.indexOf(c)    
    Element span = new Element("span")
    span.text = c.text
    c.parent.setContent(pos, span)

}

new XMLOutputter().with {
  format = Format.getRawFormat()
  format.setLineSeparator(LineSeparator.NONE)
  // XmlOutputter can write to OutputStream or Writer, which is sufficient for most cases
  output(doc, System.out)
}
Sign up to request clarification or add additional context in comments.

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.