tags:

views:

363

answers:

2

Here is the my structure:

<AllCharges>
   <Charge>
     <ID>1</ID>
     <Type>A</Type>
   </Charge>
   <Charge>
     <ID>2</ID>
     <Type>A</Type>
   </Charge>
   <Charge>
     <ID>3</ID>
     <Type>B</Type>
   </Charge>
</AllCharges>

What I want back is the full structure but I only want results in which the Type = A. The hard part I am finding is pulling back the parent xml nodes. Here is an example of what my result should look like:

<AllCharges>
   <Charge>
     <ID>1</ID>
     <Type>A</Type>
   </Charge>
   <Charge>
     <ID>2</ID>
     <Type>A</Type>
   </Charge>
</AllCharges>

I would assume the XPath would look something like this but it doesn't work: /AllCharges[//Type=A]

Is this possible?

+2  A: 

xpath does not alter the XML, it just returns results within your XML document. You can search for all 'charge' elements with type=a to get what you want.

If you want to transform the document, you'll need to look at XSL

Michael Donohue
+3  A: 
/AllCharges/Charge[Type='A']

That should do it.

The expression reads, "Select any Charge element whose parent is AllCharges, having a child element called Type whose text value is 'A'."

Tested it in the following XSLT template:

<xsl:template match="/">
  <AllCharges>
    <xsl:copy-of select="/AllCharges/Charge[Type='A']"/>
  </AllCharges>
</xsl:template>

The output was:

<AllCharges>
  <Charge>
    <ID>1</ID>
    <Type>A</Type>
  </Charge>
  <Charge>
    <ID>2</ID>
    <Type>A</Type>
  </Charge>
</AllCharges>
Welbog
Hm, this is more a XSLT solution than XPath.
mkoeller
Thanks this helped me!
sholsinger