xmlxpathmaster-detailmsxmlselectnodes

XML Master/detail data selection when master and detail are separate dataset inside the XML


Please assume the following actual XML structure (no, we cannot change it).

<root>
  <master>
    <record>
      <ID>1</ID>
      <Value>One</Value>
    </record>
    <record>
      <ID>2</ID>
      <Value>Two</Value>
    </record>
  </master>
  <detail>
    <record>
      <ID>A</ID>
      <MasterID>1</MasterID>
      <Value>Somevalue a</Value>
    </record>
    <record>
      <ID>B</ID>
      <MasterID>2</MasterID>
      <Value>Somevalue b</Value>
    </record>
    <record>
      <ID>C</ID>
      <MasterID>1</MasterID>
      <Value>Somevalue c</Value>
    </record>
    <record>
      <ID>D</ID>
      <Value>Somevalue d</Value>
    </record>
  </detail>
</root>

First we perform an XPath query on the XML to return a list of possible detail records:

detailnodes = doc.documentElement.getElementsByTagName('/root/detail')

Then we handle each returned detailrecord in the return XML nodelist, at which point we need the value of the master record based on the MasterID in the detailnode using an XPath expression only. We don't want to use application code to retreive the MasterID of the current record and then create an XPath expression based on the retreived value

Example (not like this)

for each detailnode in detailnodes do
  masterID = detailnode.ChildNodes['MasterID'].value
  masterValue = detailnode.selectNodes('../master[ID=" + MasterID + "]/Value')[0].value
end

Example (preferred way)

for each detailnode in detailnodes do
  masterValue = detailnode.selectNodes('../master[ID=?MasterID?]/Value')[0].value
end

The ?MasterID? expression inside the XPath should return the MasterID value of the current detailnode.

Is this even possible using pure XPath expressions...?

EDIT Note: I need to get this working using the MSXML DOM...


Solution

  • Seems like there is no way to do this using MSXML, so I'll need the try something else to make the X-Path more dynamic, without needing to modify code for specific XML-structures.