Removing child nodes via XSLT or Xpath - newbie question

J

jhoge123

I have an XML document that contains more information than I need for a
particular application. The structure is as follows:

<root>
<category ID = "1">
<product ID="1" />
<product ID="2" />
</category>
<category ID = "2">
<category id ="3">
<product ID ="3"/>
</category>
<category id ="4">
<product ID ="4"/>
</category>
</category>
</root>

What I want to do is populate a menu with all category nodes, but
remove all of the product nodes. I tried using "/root/category" as an
xpath, but that selects teh entire category node, along with the
product child nodes that I don't want.

Do I need to use XSLT first to remove the unwanted nodes?

Any help would be greatly appreciated.

Thanks,
John
 
M

Martin Honnen

What I want to do is populate a menu with all category nodes, but
remove all of the product nodes. I tried using "/root/category" as an
xpath, but that selects teh entire category node, along with the
product child nodes that I don't want.

Do I need to use XSLT first to remove the unwanted nodes?

XPath indeed does not change the structure at all, it simply selects a
node set in the original document and you can't exclude any child nodes
of the selected nodes. Therefore if you want to alter the structure and
for instance remove nodes you need to use XSLT (or DOM).
 
J

jhoge123

Martin,

Any idea how to make a simple XSLT file to rebuild an XML doc without a
particualar node type? Most of the XSLT tutorials I find are elaborate
descriptions of how to generate HTML from XML, and not simple
instructions on how to edit an XML file.

John
 
M

Martin Honnen

Any idea how to make a simple XSLT file to rebuild an XML doc without a
particualar node type?

Starting with the identity transformation
<http://www.w3.org/TR/xslt#copying> is often helpful:

<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

Then you simple add a template to not process a certain element at all e.g.
<xsl:template match="product" />
or to only process its child nodes e.g.
<xsl:template match="product">
<xsl:apply-templates />
</xsl:template>
or you add a template doing some other stuff you want to do with that
element.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top