简体   繁体   English

Grails XML 转换器从文件添加 XML

[英]Grails XML converter add XML from file

I'm using Grails XML converters to register custom XML marshallers for some domain classes.我正在使用 Grails XML 转换器为某些域类注册自定义 XML 编组器。

There is one class that I need to append XML from a file into the target XML like:有一个类需要将文件中的 XML 附加到目标 XML 中,例如:

<myobject>
  <field1>xxx</field1>
  <file>
    <data>..</data>
    ...
  </file>
</myobject>

Where field1 is declared on the MyObject, but the file subtree is loaded from a file.其中 field1 在 MyObject 上声明,但文件子树是从文件加载的。

I found two ways of doing this, both are escaping the tags for the file subtree generating:我找到了两种方法,都可以转义文件子树生成的标签:

<myobject>
  <field1>xxx</field1>
  &lt;file&gt;
    &lt;data&gt;..&lt;/data&gt;
    ...
  &lt;/file&gt;
</myobject>

These methods where with convertAnother and with chars, both produce the same result:这些使用 convertAnother 和 chars 的方法都产生相同的结果:

XML.registerObjectMarshaller(MyObject) { o, xml ->

   def _file = new File(o.file_name)

   xml.build {
      field1(o.field1)

      xml.startNode 'file'

         //xml.convertAnother vf.text
         xml.chars vf.text

      xml.end()
   }
}

Is it possible to add the contents of the file but unescaped?是否可以添加文件的内容但未转义?

The only way I found that works is by using the internal writer API of the XML builder:我发现有效的唯一方法是使用 XML 构建器的内部编写器 API:

My code looks exactly like this:我的代码看起来完全像这样:

it.registerObjectMarshaller(Contribution) { contribution, xml ->
            xml.attribute 'xsi:type', 'CONTRIBUTION'
            xml.build {
               uid {
                  value(contribution.uid)
               }
               contribution.versions.each { version ->

                  def xml_version = new File(version.fileLocation).text

                  // remove any internal xml and namespace declaration
                  xml_version = xml_version.replaceFirst('<\\?xml version="1.0" encoding="UTF-8"\\?>', '')
                  xml_version = xml_version.replaceFirst('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"', '')
                  xml_version = xml_version.replaceFirst('xmlns="http://schemas.openehr.org/v1"', '')

                  // change version for versions
                  xml_version = xml_version.replaceFirst(/<version( )*/, '<versions ')
                  xml_version = xml_version.replaceFirst('</version>', '</versions>')

                  // this is what outputs the exact text in the XML
                  xml.writer.mode = org.grails.web.xml.XMLStreamWriter.Mode.CONTENT
                  xml.writer.writer.unescaped().write(xml_version)
               }
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM