I have an XML value and an XPath query like this:
XML:
<Firms>
<Firm id="1" select="1" update="1" insert="1" delete="1">
<Backoffice select="1" update="1" insert="1" delete="1">
<Transaction select="1" update="1" insert="1" delete="0">
<DatePeriod startDate="20110101" endDate="20110505" select="1" update="0" insert="0" delete="0"/>
<DatePeriod startDate="20100101" endDate="20110101" select="0" update="0" insert="0" delete="0"/>
</Transaction>
</Backoffice>
</Firm>
</Firms>
XPath:
./Firms/Firm[@id="1"]/Backoffice/Transaction/DatePeriod
I want to get values of the longest prefix of XPath, contained in XML.
In my example the values would be:
<DatePeriod startDate="20110101" endDate="20110505" select="1" update="0" insert="0" delete="0"/>
<DatePeriod startDate="20100101" endDate="20110101" select="0" update="0" insert="0" delete="0"/>
If we change the XPath to
./Firms/Firm[@id="1"]/Backoffice/Client/Account
the expected result should be
<Firms>
<Firm id="1" select="1" update="1" insert="1" delete="1">
<Backoffice select="1" update="1" insert="1" delete="0"/>
</Firm>
</Firms>
Let me explain what is going on. The XML describes user’s privileges, the XPath describes the security context (the securable object). First we try to find out if there is an exact rule about the object (./Firms/Firm[@id="1"]/Backoffice/Client/Account) and check the expected rights (select, insert or update). If we don’t find it we go to the parent level (./Firms/Firm[@id="1"]/Backoffice/Client) and try to apply the uplevel rules (if they exist). And so on. Finally we find the existing level (./Firms/Firm[@id="1"]/Backoffice) and see that the parent rule gives us the rights to select, update, but not to delete.
Is there a way to implement this logic via XPath (for SQL Server 2008)?
The only way that I can think of doing this is by programmatically try-and-fail:
you build your most specific XPath expression (
./Firms/Firm[@id="1"]/Backoffice/Client/Account); let’s call itXyou use
Xto find matching nodes; if you find any, then you’ve finished, otherwise you go to step 3.if you can generalize
Xby removing the last part of it, then do it and go to step 2; otherwise you can’t find any match in your XML, and you probably want to raise an error.I can’t help on how to do this with SQL Server 2008, sorry.