如何使用groovy在XML中搜索+替换?

时间:2022-05-25 16:49:28

How do I use groovy to search+replace in XML?

如何使用groovy在XML中搜索+替换?

I need something as short/easy as possible, since I'll be giving this code to the testers for their SoapUI scripting.

我需要尽可能短/容易的东西,因为我将把这些代码提供给测试人员用于他们的SoapUI脚本。

More specifically, how do I turn:

更具体地说,我该怎么转:

<root><data></data></root>

into:

<root><data>value</data></root>

9 个解决方案

#1


2  

Some of the stuff you can do with an XSLT you can also do with some form of 'search & replace'. It all depends on how complex your problem is and how 'generic' you want to implement the solution. To make your own example slightly more generic:

您可以使用XSLT执行某些操作,也可以使用某种形式的“搜索和替换”。这完全取决于您的问题有多复杂以及您希望如何实现解决方案。为了使您自己的示例稍微更通用:

xml.replaceFirst("<Mobiltlf>[^<]*</Mobiltlf>", '<Mobiltlf>32165487</Mobiltlf>')

The solution you choose is up to you. In my own experience (for very simple problems) using simple string lookups is faster than using regular expressions which is again faster than using a fullblown XSLT transformation (makes sense actually).

您选择的解决方案取决于您。根据我自己的经验(对于非常简单的问题),使用简单的字符串查找比使用正则表达式更快,这比使用完整的XSLT转换更快(实际上是有意义的)。

#2


1  

After some frenzied coding i saw the light and did like this

经过一些疯狂的编码,我看到了光,并做了这样的

import org.custommonkey.xmlunit.Diff
import org.custommonkey.xmlunit.XMLUnit

def input = '''<root><data></data></root>'''
def expectedResult = '''<root><data>value</data></root>'''

def xml = new XmlParser().parseText(input)

def p = xml.'**'.data
p.each{it.value="value"}

def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(xml)
def result = writer.toString()

XMLUnit.setIgnoreWhitespace(true)
def xmlDiff = new Diff(result, expectedResult)
assert xmlDiff.identical()

Unfortunately this will not preserve the comments and metadata etc, from the original xml document, so i'll have to find another way

不幸的是,这不会保留原始xml文档中的注释和元数据等,所以我必须找到另一种方法

#3


1  

I did some some testing with DOMCategory and it's almost working. I can make the replace happen, but some infopath related comments disappear. I'm using a method like this:

我用DOMCategory做了一些测试,它几乎正常工作。我可以让替换发生,但一些infopath相关的评论消失了。我正在使用这样的方法:

def rtv = { xml, tag, value ->
    def doc     = DOMBuilder.parse(new StringReader(xml))
    def root    = doc.documentElement
    use(DOMCategory) { root.'**'."$tag".each{it.value=value} }
    return DOMUtil.serialize(root)    
}

on a source like this:

在这样的来源:

<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://corp.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf></Mobiltlf>
  <E-mail-adresse></E-mail-adresse>
</application:FA_Ansoegning>

The only thing missing from the result are the <?mso- lines from the result. Anyone with an idea for that?

结果中唯一缺少的是结果中的

#4


1  

That's the best answer so far and it gives the right result, so I'm going to accept the answer :) However, it's a little too large for me. I think i had better explain that the alternative is:

这是迄今为止最好的答案,它给出了正确的结果,所以我会接受答案:)但是,这对我来说有点太大了。我想我最好解释一下,替代方案是:

xml.replace("<Mobiltlf></Mobiltlf>", <Mobiltlf>32165487</Mobiltlf>")

But that's not very xml'y so I thought i'd look for an alternative. Also, I can't be sure that the first tag is empty all the time.

但那不是很简单,所以我想我会寻找另一种选择。另外,我不能确定第一个标签是否一直是空的。

#5


1  

To retain the attributes just modify your little program like this (I've included a sample source to test it):

要保留属性,只需像这样修改你的小程序(我已经包含了一个示例源来测试它):

def input = """
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf  type="national" anotherattribute="value"></Mobiltlf>
  <E-mail-adresse attr="whatever"></E-mail-adresse>
</application:FA_Ansoegning>
""".trim()

def rtv = { xmlSource, tagName, newValue ->
    regex = "(<$tagName[^>]*>)([^<]*)(</$tagName>)"
    replacement = "\$1${newValue}\$3"
    xmlSource = xmlSource.replaceAll(regex, replacement)
    return xmlSource
}

input = rtv( input, "Mobiltlf", "32165487" )
input = rtv( input, "E-mail-adresse", "bob@email.com" )
println input

Running this script produces:

运行此脚本会产生:

<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf  type="national" anotherattribute="value">32165487</Mobiltlf>
  <E-mail-adresse attr="whatever">bob@email.com</E-mail-adresse>
</application:FA_Ansoegning>

Note that the matching regexp now contains 3 capturing groups: (1) the start tag (including attributes), (2) whatever is the 'old' content of your tag and (3) the end tag. The replacement string refers to these captured groups via the $i syntax (with backslashes to escape them in the GString). Just a tip: regular expressions are very powerful animals, it's really worthwile to become familiar with them ;-) .

请注意,匹配的正则表达式现在包含3个捕获组:(1)开始标记(包括属性),(2)标记的“旧”内容和(3)结束标记。替换字符串通过$ i语法引用这些捕获的组(使用反斜杠在GString中转义它们)。只是一个提示:正则表达式是非常强大的动物,熟悉它们真的很值得;-)。

#6


0  

check this: http://today.java.net/pub/a/today/2004/08/12/groovyxml.html?page=2

检查一下:http://today.java.net/pub/a/today/2004/08/12/groovyxml.html?page = 2

#7


0  

Three "official" groovy ways of updating XML are described on page http://groovy.codehaus.org/Processing+XML, section "Updating XML".

http://groovy.codehaus.org/Processing+XML,“更新XML”一节中介绍了三种“官方”常规更新XML的方法。

Of that three it seems only DOMCategory way preserves XML comments etc.

在这三个中,似乎只有DOMCategory方式保留XML注释等。

#8


0  

To me the actual copy & search & replace seems like the perfect job for an XSLT stylesheet. In an XSLT you have no problem at all to just copy everything (including the items you're having problems with) and simply insert your data where it is required. You can pass the specific value of your data in via an XSL parameter or you can dynamically modify the stylesheet itself (if you include as a string in your Groovy program). Calling this XSLT to transform your document(s) from within Groovy is very simple.

对我来说,实际的复制和搜索和替换似乎是XSLT样式表的完美工作。在XSLT中,您完全没有问题只需复制所有内容(包括您遇到问题的项目),只需将数据插入到需要的地方即可。您可以通过XSL参数传递数据的特定值,也可以动态修改样式表本身(如果在Groovy程序中包含为字符串)。调用此XSLT从Groovy中转换文档非常简单。

I quickly cobbled the following Groovy script together (but I have no doubts it can be written even more simple/compact):

我快速拼凑了下面的Groovy脚本(但我毫不怀疑它可以写得更简单/紧凑):

import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource

def xml = """
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf></Mobiltlf>
  <E-mail-adresse></E-mail-adresse>
</application:FA_Ansoegning>
""".trim()

def xslt = """
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:param name="mobil" select="'***dummy***'"/>
    <xsl:param name="email" select="'***dummy***'"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Mobiltlf">
        <xsl:copy>
            <xsl:value-of select="\$mobil"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="E-mail-adresse">
        <xsl:copy>
            <xsl:value-of select="\$email"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
""".trim()

def factory = TransformerFactory.newInstance()
def transformer = factory.newTransformer(new StreamSource(new StringReader(xslt)))

transformer.setParameter('mobil', '1234567890')
transformer.setParameter('email', 'john.doe@foobar.com')

transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(System.out))

Running this script produces:

运行此脚本会产生:

<?xml version="1.0" encoding="UTF-8"?><?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:application="http://ementor.dk/application/2007/06/22/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf>1234567890</Mobiltlf>
  <E-mail-adresse>john.doe@foobar.com</E-mail-adresse>
</application:FA_Ansoegning>

#9


0  

Brilliant! Thank you very much for you assistance :)

辉煌!非常感谢你的帮助:)

That solves my problem in a much cleaner and easier way. It's ended up looking like this:

这以更清洁,更简单的方式解决了我的问题。结果看起来像这样:

def rtv = { xmlSource, tagName, newValue ->
    regex = "<$tagName>[^<]*</$tagName>"
    replacement = "<$tagName>${newValue}</$tagName>"
    xmlSource = xmlSource.replaceAll(regex, replacement)
    return xmlSource
}

input = rtv( input, "Mobiltlf", "32165487" )
input = rtv( input, "E-mail-adresse", "bob@email.com" )
println input

Since I'm giving this to our testers for use in their testing tool SoapUI, I've tried to "wrap" it, to make it easier for them to copy and paste.

由于我将这个给我们的测试人员用于他们的测试工具SoapUI,我试图“包装”它,以便他们更容易复制和粘贴。

This is good enough for my purpose, but it would be perfect if we could add one more "twist"

这对我的目的来说已经足够了,但如果我们再添加一个“扭曲”它将是完美的

Let's say the input had this in it...

让我们说输入中有这个......

<Mobiltlf type="national" anotherattribute="value"></Mobiltlf>

...and we wanted to retain thos two attributes even though we replaced the value. Is there a way to use regexp for that too?

......我们想要保留两个属性,即使我们替换了这个值。有没有办法使用正则表达式呢?

#1


2  

Some of the stuff you can do with an XSLT you can also do with some form of 'search & replace'. It all depends on how complex your problem is and how 'generic' you want to implement the solution. To make your own example slightly more generic:

您可以使用XSLT执行某些操作,也可以使用某种形式的“搜索和替换”。这完全取决于您的问题有多复杂以及您希望如何实现解决方案。为了使您自己的示例稍微更通用:

xml.replaceFirst("<Mobiltlf>[^<]*</Mobiltlf>", '<Mobiltlf>32165487</Mobiltlf>')

The solution you choose is up to you. In my own experience (for very simple problems) using simple string lookups is faster than using regular expressions which is again faster than using a fullblown XSLT transformation (makes sense actually).

您选择的解决方案取决于您。根据我自己的经验(对于非常简单的问题),使用简单的字符串查找比使用正则表达式更快,这比使用完整的XSLT转换更快(实际上是有意义的)。

#2


1  

After some frenzied coding i saw the light and did like this

经过一些疯狂的编码,我看到了光,并做了这样的

import org.custommonkey.xmlunit.Diff
import org.custommonkey.xmlunit.XMLUnit

def input = '''<root><data></data></root>'''
def expectedResult = '''<root><data>value</data></root>'''

def xml = new XmlParser().parseText(input)

def p = xml.'**'.data
p.each{it.value="value"}

def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(xml)
def result = writer.toString()

XMLUnit.setIgnoreWhitespace(true)
def xmlDiff = new Diff(result, expectedResult)
assert xmlDiff.identical()

Unfortunately this will not preserve the comments and metadata etc, from the original xml document, so i'll have to find another way

不幸的是,这不会保留原始xml文档中的注释和元数据等,所以我必须找到另一种方法

#3


1  

I did some some testing with DOMCategory and it's almost working. I can make the replace happen, but some infopath related comments disappear. I'm using a method like this:

我用DOMCategory做了一些测试,它几乎正常工作。我可以让替换发生,但一些infopath相关的评论消失了。我正在使用这样的方法:

def rtv = { xml, tag, value ->
    def doc     = DOMBuilder.parse(new StringReader(xml))
    def root    = doc.documentElement
    use(DOMCategory) { root.'**'."$tag".each{it.value=value} }
    return DOMUtil.serialize(root)    
}

on a source like this:

在这样的来源:

<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://corp.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf></Mobiltlf>
  <E-mail-adresse></E-mail-adresse>
</application:FA_Ansoegning>

The only thing missing from the result are the <?mso- lines from the result. Anyone with an idea for that?

结果中唯一缺少的是结果中的

#4


1  

That's the best answer so far and it gives the right result, so I'm going to accept the answer :) However, it's a little too large for me. I think i had better explain that the alternative is:

这是迄今为止最好的答案,它给出了正确的结果,所以我会接受答案:)但是,这对我来说有点太大了。我想我最好解释一下,替代方案是:

xml.replace("<Mobiltlf></Mobiltlf>", <Mobiltlf>32165487</Mobiltlf>")

But that's not very xml'y so I thought i'd look for an alternative. Also, I can't be sure that the first tag is empty all the time.

但那不是很简单,所以我想我会寻找另一种选择。另外,我不能确定第一个标签是否一直是空的。

#5


1  

To retain the attributes just modify your little program like this (I've included a sample source to test it):

要保留属性,只需像这样修改你的小程序(我已经包含了一个示例源来测试它):

def input = """
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf  type="national" anotherattribute="value"></Mobiltlf>
  <E-mail-adresse attr="whatever"></E-mail-adresse>
</application:FA_Ansoegning>
""".trim()

def rtv = { xmlSource, tagName, newValue ->
    regex = "(<$tagName[^>]*>)([^<]*)(</$tagName>)"
    replacement = "\$1${newValue}\$3"
    xmlSource = xmlSource.replaceAll(regex, replacement)
    return xmlSource
}

input = rtv( input, "Mobiltlf", "32165487" )
input = rtv( input, "E-mail-adresse", "bob@email.com" )
println input

Running this script produces:

运行此脚本会产生:

<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf  type="national" anotherattribute="value">32165487</Mobiltlf>
  <E-mail-adresse attr="whatever">bob@email.com</E-mail-adresse>
</application:FA_Ansoegning>

Note that the matching regexp now contains 3 capturing groups: (1) the start tag (including attributes), (2) whatever is the 'old' content of your tag and (3) the end tag. The replacement string refers to these captured groups via the $i syntax (with backslashes to escape them in the GString). Just a tip: regular expressions are very powerful animals, it's really worthwile to become familiar with them ;-) .

请注意,匹配的正则表达式现在包含3个捕获组:(1)开始标记(包括属性),(2)标记的“旧”内容和(3)结束标记。替换字符串通过$ i语法引用这些捕获的组(使用反斜杠在GString中转义它们)。只是一个提示:正则表达式是非常强大的动物,熟悉它们真的很值得;-)。

#6


0  

check this: http://today.java.net/pub/a/today/2004/08/12/groovyxml.html?page=2

检查一下:http://today.java.net/pub/a/today/2004/08/12/groovyxml.html?page = 2

#7


0  

Three "official" groovy ways of updating XML are described on page http://groovy.codehaus.org/Processing+XML, section "Updating XML".

http://groovy.codehaus.org/Processing+XML,“更新XML”一节中介绍了三种“官方”常规更新XML的方法。

Of that three it seems only DOMCategory way preserves XML comments etc.

在这三个中,似乎只有DOMCategory方式保留XML注释等。

#8


0  

To me the actual copy & search & replace seems like the perfect job for an XSLT stylesheet. In an XSLT you have no problem at all to just copy everything (including the items you're having problems with) and simply insert your data where it is required. You can pass the specific value of your data in via an XSL parameter or you can dynamically modify the stylesheet itself (if you include as a string in your Groovy program). Calling this XSLT to transform your document(s) from within Groovy is very simple.

对我来说,实际的复制和搜索和替换似乎是XSLT样式表的完美工作。在XSLT中,您完全没有问题只需复制所有内容(包括您遇到问题的项目),只需将数据插入到需要的地方即可。您可以通过XSL参数传递数据的特定值,也可以动态修改样式表本身(如果在Groovy程序中包含为字符串)。调用此XSLT从Groovy中转换文档非常简单。

I quickly cobbled the following Groovy script together (but I have no doubts it can be written even more simple/compact):

我快速拼凑了下面的Groovy脚本(但我毫不怀疑它可以写得更简单/紧凑):

import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource

def xml = """
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:application="http://ementor.dk/application/2007/06/22/"
xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf></Mobiltlf>
  <E-mail-adresse></E-mail-adresse>
</application:FA_Ansoegning>
""".trim()

def xslt = """
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:param name="mobil" select="'***dummy***'"/>
    <xsl:param name="email" select="'***dummy***'"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Mobiltlf">
        <xsl:copy>
            <xsl:value-of select="\$mobil"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="E-mail-adresse">
        <xsl:copy>
            <xsl:value-of select="\$email"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
""".trim()

def factory = TransformerFactory.newInstance()
def transformer = factory.newTransformer(new StreamSource(new StringReader(xslt)))

transformer.setParameter('mobil', '1234567890')
transformer.setParameter('email', 'john.doe@foobar.com')

transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(System.out))

Running this script produces:

运行此脚本会产生:

<?xml version="1.0" encoding="UTF-8"?><?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-" href="manifest.xsf" solutionVersion="1.0.0.14" productVersion="12.0.0" PIVersion="1.0.0.0" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<application:FA_Ansoegning xmlns:application="http://ementor.dk/application/2007/06/22/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/200    8-04-14T14:31:48">
    <Mobiltlf>1234567890</Mobiltlf>
  <E-mail-adresse>john.doe@foobar.com</E-mail-adresse>
</application:FA_Ansoegning>

#9


0  

Brilliant! Thank you very much for you assistance :)

辉煌!非常感谢你的帮助:)

That solves my problem in a much cleaner and easier way. It's ended up looking like this:

这以更清洁,更简单的方式解决了我的问题。结果看起来像这样:

def rtv = { xmlSource, tagName, newValue ->
    regex = "<$tagName>[^<]*</$tagName>"
    replacement = "<$tagName>${newValue}</$tagName>"
    xmlSource = xmlSource.replaceAll(regex, replacement)
    return xmlSource
}

input = rtv( input, "Mobiltlf", "32165487" )
input = rtv( input, "E-mail-adresse", "bob@email.com" )
println input

Since I'm giving this to our testers for use in their testing tool SoapUI, I've tried to "wrap" it, to make it easier for them to copy and paste.

由于我将这个给我们的测试人员用于他们的测试工具SoapUI,我试图“包装”它,以便他们更容易复制和粘贴。

This is good enough for my purpose, but it would be perfect if we could add one more "twist"

这对我的目的来说已经足够了,但如果我们再添加一个“扭曲”它将是完美的

Let's say the input had this in it...

让我们说输入中有这个......

<Mobiltlf type="national" anotherattribute="value"></Mobiltlf>

...and we wanted to retain thos two attributes even though we replaced the value. Is there a way to use regexp for that too?

......我们想要保留两个属性,即使我们替换了这个值。有没有办法使用正则表达式呢?