Re: Extracting information from XML

Daniel Dekany <[email protected]>
Newsgroups gmane.comp.web.freemarker.user
Message-ID <[email protected]>
Tuesday, June 1, 2010, 4:26:07 PM, Eric Willigers wrote:

> Hello,
>
> I'm trying to extract information from some XML files, but I'm 
> encountering a couple of unusual cases (below).
>
> Any suggestions are welcome.
>
> Lots of thanks,
> Eric.
>
>
>
> Question 1.
>
> We want to extract "hyphenated-name" nodes from some XML:-
>
> <root>
>      <hyphenated-name data="first"/>
>      <hyphenated-name data="second"/>
> </root>
>
> I would like to use
>      <#list document.root.hyphenated-name as node>
> but the hyphen prevents this from working. None of these work either:-
>      <#list document.root."hyphenated-name" as node>
>      <#list document.root.'hyphenated-name' as node>
>      <#list document.root.`hyphenated-name` as node>

I find it strange that people always try to accidentally hit the right
syntax... there is a documentation! Anyway, the thing to know here is
that foo.bar and foo["bar"] is the same. So the solution is:

  <#list document.root["hyphenated-name"] as node>

> I ended up using
>      <#list document.root?children as child>
>        <#if child?node_type = 'element' && child?node_name = 
"hyphenated-name">>
>
> Are there better options?
>
>
>
>
> Question 2.
>
> How should I extract an attribute from an XML node, when the name of the
> attribute is given by a variable?
> e.g. is there something like ${node.@$attrName}
>
>
> Here's my XML:-
>
> <root>
>      <attr name="a" />
>      <attr name="b" />
>
>      <data b="B" a="A" />
> </root>
>
>
> I tried
>
> <#list document.root.data as data>
>    <#list document.root.attr as attr>
>      ${data.@$attr.@name}
>    </#list>
> </#list>
>
> but this caused
> SEVERE: javax.xml.transform.TransformerException: A node test that 
> matches either NCName:* or QName was expected.
>
> A bug?

No, the problem is that the $ thingy is not resolved there, it never
was. Actually, $foo is never resolved in FreeMarker, only ${foo}, but
even that only in static text parts and in string literals. So this is
again a [] thing. You can have any kind of complex expression inside
[] as far as it evaluates to a string, so: ${data["@" + attr.@name]}

-- 
Best regards,
 Daniel Dekany


------------------------------------------------------------------------------
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.