我正在使用groovy,所以java实现也没关系。
我有
"""<TextFlow fontFamily="Arial" fontSize="20"><span>before</span>Less than 7 days<span>after</span></TextFlow>"""
我想用标记包装第一级文本节点。所以我想得到
"""<TextFlow fontFamily="Arial" fontSize="20"><span>before</span><span>Less than 7 days</span><span>after</span></TextFlow>"""
我已经研究过不处理文本节点的XmlSlurper。我也研究了可以处理文本节点的XmlParser,但我不知道如何用xml元素替换它。请指教。
答案 0 :(得分:1)
这对我有用,希望它能帮助别人
@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)
}