Apache Freemarker-从xPath列表中获取节点名称 [英] Apache Freemarker - Get node name from an xPath list

查看:206
本文介绍了Apache Freemarker-从xPath列表中获取节点名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,其中我正在用Freemarker处理名称空间xml.下面是我使用xPath方法处理的结构.

I have a use case wherein I am processing a namespace xml with Freemarker. Below is the structure that I am processing using xPath approach.

<ns3:Books>
<ns3:BookName>Book ABC</ns3:BookName>
<ns3:BookId>1857669</ns3:BookId>
<ns3:BookAuthor>John Doe</ns3:BookAuthor>
</ns3:Books> 

我能够使用以下方法获取子节点列表 <#list xml['//Books/*'] as p>. 我尝试了以下方法:

I am able to get the list of child nodes using <#list xml['//Books/*'] as p>. I tried the below way:

<#list xml['//Books/*'] as p>
${p["BookName"]}
</#list>

上面的代码片段无法从xPath列表中获取节点名称. 如何从列表中访问各个子节点名称BookName,BookId,BookAuthor?

The above code snippet is not able to get the node name from the xPath list. How can I access the individual child node names BookName,BookId,BookAuthor from the list?

推荐答案

在这种情况下,您有一个带有名称空间的xml,并且在创建xpath表达式时必须考虑到这一点.

In this case, you have an xml with namespaces, and you have to take that into account in creating your xpath expression.

因此,首先,您的实际xml可能看起来像这样:

So, first, your actual xml would probably look something like this:

xml = <ns3:Books xmlns:ns3="http://example.com/whatever">>    
<ns3:BookName>Book ABC</ns3:BookName>    
<ns3:BookId>1857669</ns3:BookId>    
<ns3:BookAuthor>John Doe</ns3:BookAuthor> 
</ns3:Books>

您的模板还必须考虑名称空间.完成此操作后,您可以按其标记名称访问xml中的各个节点并提取文本.可能比下面的方法更短地完成您想要的工作,但这将为您分别提供每个元素:

Your template also has to take namespaces into account. Once you do that, you can access the individual nodes in the xml by their tag name and extract the text. There may be a shorter way of doing what you want than the one below, but this will give you each element separately:

<#ftl ns_prefixes={"ns3":"http://example.com/whatever"}>

  <#list xml[".//ns3:Books//ns3:BookName/text()"] as name>
    ${name}
   </#list>

  <#list xml[".//ns3:Books//ns3:BookId/text()"] as id>
    ${id}
   </#list>

  <#list xml[".//ns3:Books//ns3:BookAuthor/text()"] as author>
    ${author}
   </#list>

输出:

  Book ABC

1857669

John Doe

这篇关于Apache Freemarker-从xPath列表中获取节点名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆