【问题标题】:xml string manipulation in velocityxml 字符串操作速度
【发布时间】:2013-08-09 18:32:54
【问题描述】:

我有一个带有 XML 标签的字符串

<?XML version="1.0" encoding="UTF-8"?>
<s-d-structure> <heading>This is title</heading> <main> <cad> <bad>this is formatted html</bad> <name>some text </name> <title>show</title> </cad> </main> </s-d-structure>

我想获取所有标签之间的内容以及没有打开标签和结束标签的标签。

输出应该是

不好:这是格式化的 html

名称:一些文字

标题:显示

如何在我的速度模板文件中执行此操作

【问题讨论】:

    标签: javascript velocity


    【解决方案1】:

    Velocity 是一种模板语言,几乎没有编程能力。它通常用于生成 XML,而不是处理它们。 VTL 本身不能用于此,但鉴于您可以将任何 Java 对象放在上下文中,您可以使用知道如何将 XML 字符串解析为 DOM 的工具,您可以进一步处理它。 Velocity Tools 已经有一个 XmlTool,您可以启用和使用它。

    如果你不能在你的项目中配置工具,那么你可以尝试一个简单的字符串处理,虽然这很脆弱。别忘了 Velocity 中的变量是真正的 Java 对象,任何公共方法都可以被调用:

    #set ($xml = '<?xml version="1.0" encoding="UTF-8"?>
        <s-d-structure> <heading>This is title</heading>
          <main> <cad>
            <bad>this is formatted html</bad>
            <name>some text </name>
            <title>show</title>
          </cad> </main>
        </s-d-structure>')
    ## Extract only the main content
    #set ($xml = $xml.replaceFirst('(?s).*<cad>(.*)</cad>.*', '$1'))
    
    ## There's no #while in Velocity, so we just loop long enough
    #foreach ($i in [0..10000])
      ## Extract the first tag
      $xml.replaceFirst('(?s)\s*+<([^>]++)>([^<]*+)</.*+', '$1: $2')
      #set ($xml = $xml.replaceFirst('(?s)\s*+<[^>]++>[^<]*+</[^>]++>(.*+)', '$1'))
      #if ($xml.trim() == '')
        ## Stop the foreach once the string is empty
        #break($foreach)
      #end
    #end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      相关资源
      最近更新 更多