Update: a more detailed example.
The first two proposed solutions were correct in accordance with what I tried to say not to do. I canโt know the location; it should be able to look at the entire document tree. Thus, the solution in these lines with / Books /, set as context, will not work:
SELECT x.query('.') FROM @xml.nodes('/Books/*[not(@ID) or @ID = 5]') x1(x)
Original question with best example:
Using the implementation of SQL Server 2005 XQuery, I need to select all the nodes in the XML document only once and keep their original structure, but only if they do not have a specific attribute or this attribute has a specific value (passed to the parameter). The request should also work on the entire XML document (the axis of the child or on its own), and not at a given depth.
That is, each individual node will be displayed in the resulting document only if it and each of its ancestors lack an attribute or have an attribute with a single specific value.
For example:
If it was XML:
DECLARE @Xml XML SET @Xml = N' <Library> <Novels> <Novel category="1">Novel1</Novel> <Novel category="2">Novel2</Novel> <Novel>Novel3</Novel> <Novel category="4">Novel4</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>AF</Volume> <Volume category="2">GL</Volume> <Volume category="3">MS</Volume> <Volume category="4">TZ</Volume> </Encyclopedia> </Encyclopedias> <Dictionaries category="1"> <Dictionary>Webster</Dictionary> <Dictionary>Oxford</Dictionary> </Dictionaries> </Library> '
Parameter 1 for the category will result in the following:
<Library> <Novels> <Novel category="1">Novel1</Novel> <Novel>Novel3</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>AF</Volume> </Encyclopedia> </Encyclopedias> <Dictionaries category="1"> <Dictionary>Webster</Dictionary> <Dictionary>Oxford</Dictionary> </Dictionaries> </Library>
Parameter 2 for the category will result in the following:
<Library> <Novels> <Novel category="2">Novel2</Novel> <Novel>Novel3</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>AF</Volume> <Volume category="2">GL</Volume> </Encyclopedia> </Encyclopedias> </Library>
I know XSLT is great for this job, but it is not an option. We have to do this all the way in SQL Server 2005. Any implementations that don't use XQuery are great too, if you can do it all in T-SQL.
sql-server xquery xpath axes
phloopy
source share