Subject:Need XPath to return just immediate child nodes Author:Jeff Michaels Date:17 Apr 2007 04:18 PM
Hello,
Even though this is an XQuery forum, I believe XPath 2.o is a subset of XQuery, and so I will go ahead and ask this question...
I have been working feverishly to come up with an XPath expression that returns just 1-level deep of child nodes, and *no* grandchildren, along with those child nodes' attributes.
I want to return those Product categories just under <Products> and to exclude <Products> element itself. Also, the child element names will not be known up front.
The requirement is to not have any grandchild nodes and to include all child attributes...
If I execute an XPath expression of: //Products/* or //Products/child::node() or //Products/child::element(), I get child, grandchild, etc {a subtree}.
How do I get just the immediate children of a given node/element, along with it's attributes...?
Subject:Need XPath to return just immediate child nodes Author:Minollo I. Date:17 Apr 2007 04:28 PM
I don't think you can do that using XPath; XPath will return nodes matching your expression; and those nodes will still contain the sub-elements defined in the queried fragment.
On the other hand, I'm not sure why that's a problem; //Products/* won't return two elements, say <software>, <home>; it will return one element, <software><home>...</home></software>, where <home> is a child of the <software> element. What you do with that result downstream should take care of ignoring children elements of the elements returned by //Products/*
If you really need to have a "clean" sequence of only the top level children of Products, you would have to switch to XQuery, that will help you building the XML result the way you want.
return
<output>
name={$name}
attrs=
{
for $a in $attrs
let $attrName := fn:local-name($a)
let $attrVal := fn:string($a)
return <attr>$attrName $attrVal</attr>
}
</output>
...In this example i am not yet trying to create the final output, but just trying to grab each attribute node's name and value.
...but this is not working, as the attributes that I grab, don't seem to list out; the return value of the nested FLWOR statement is empty. My other issue is that I cannot seem to create the node name like:
<{$name}>
</{$name}>
I get nasty syntax error stating: XQuery syntax error in #...ttrVal</attr> } </output> <{$#: Unexpected token "{" in path expression MCC/xml test.xq line 19 1176849281368 202154
It apparently doesn't like using a variable to create an element name...