向XML添加特殊字符

时间:2013-10-09 17:23:41

标签: xml groovy

尝试将&添加为元素值之一,但StreamMarkupBuilder无法识别&&
代码

def buildXml {
   def requestXml = {
     RootElement {
        Element1("&Value1")
        Element2("Value2")
     }
   }
 return new StreamingMarkupBuilder().bind(requestXml)
}

输出

<RootElement>
  <Element1>&amp;Value1</Element1>
  <Element2>Value2</Element2>
</RootElement>

预期输出

<RootElement>
      <Element1>&Value1</Element1>
      <Element2>Value2</Element2>
</RootElement>

我遇到了MarkupBuilder的{​​{1}}方法。 Doc说

setEscapeAttributes()

寻找类似Defaults to true. If set to false then you must escape any special characters within attribute values such as '&', '<', CR/LF, single and double quotes etc. manually as needed. The builder will not guard against producing invalid XML when in this mode and the output may not be able to be parsed/round-tripped but it does give you full control when producing for instance HTML output.

的内容

1 个答案:

答案 0 :(得分:1)

你应该对你所拥有的一切都很好。我第二个吉姆和mzjn。最终遗留系统将解析xml以获得期望从&开始:

def requestXml = {
  RootElement {
     Element1("&Value1")
     Element2("Value2")
  }
}

def xml = new groovy.xml.StreamingMarkupBuilder().bind(requestXml)

//Legacy backend reading/parsing the xml 
//should reads escaped characters appropriately.
def slurper = new XmlSlurper().parseText(xml.toString())
assert slurper.Element1 == "&Value1"