Reputation: 161
I have xml similar to the one below:
<?xml version='1.0' encoding='utf-8'?>
<Document>
<name>SMTH</name>
<Group>
<GroupHeader>Some Description</GroupHeader>
<Port>
<ID>13553</PortID>
<Name>Some name</PortName>
<Number>PO1005</WorldPortNumber>
<Section>
<SectionHeader ID="63">General overview</SectionHeader>
<PAR ID="59341" updatedate="19/05/2010 08:35:51">Important data</PAR>
</Section>
<Section>
<SectionHeader ID="66">Max size</SectionHeader>
<PAR ID="59344" updatedate="19/05/2010 08:35:51">Important data</PAR>
</Section>
</Port>
</Group>
</Document>
I would like to select all the Port nodes including only ID, Name, Number and PAR children nodes (rest of the children node should be ignored). Result should be just a collection of Port nodes including those 4 children nodes I listed above. Here is what is should look like:
Port:
ID=234234
Name=blabla
Number=324234
PAR=sdfsdfs
PAR=fgfgfg
Port:
ID=5555
Name=blabla
Number=ghfh
PAR=sdfsdfs
PAR=fgfgfg
...
Many thanks!
Upvotes: 0
Views: 346
Reputation: 6956
What you request is impossible to achieve with a single XPath expression.
An XPath expression selects a node or nodeset as it exists in the document. If you use XPath to select a Port
element, then that element will be returned to you unmodified, with all of its existing document context, including its parent and children.
You could select each of the descendent elements independently of Port
, using a union |
, or, you could select each of the Port
elements, then with each Port
as the context, select only those descendants you want to use (or remove/ignore those descendents you don't want).
How you do this will depend on what you intend to do with the nodes when you have retrieved them. If you wish to produce the example output from the input, then XSLT may be a good choice.
Upvotes: 1
Reputation: 76
Somthing like:
<xsl:for-each select="//Port">
<xsl:copy-of select="*[name()='ID' or name()='Name' or name()='Number']"></xsl:copy-of>
<xsl:copy-of select="Section/*[name()='PAR']"></xsl:copy-of>
</xsl:for-each>
Hope that helps. :)
Regards, Harrie
Upvotes: 2