liveBook · Manning

Xml shredding

As explained in 100 SQL Server Mistakes and How to Avoid Them

XML shredding is the process of extracting data from XML markup and organizing it into relational values.

XML shredding extracts markup into relational values. It can seem reasonable to shred an incoming document into tables and later reconstruct XML, especially when the data resembles ordinary employee records. section 3.4.1

Mistake 1: treating every XML exchange as a relational-storage problem. In the MagicChoc scenario, historic employee contracts require Employees, ContractHistory, Skills, and ContractSkills tables to avoid duplicated data. That design applies normalization, but converting XML into relational data and back again required substantial fiddling and 83 ms of combined processing time. section 3.4.1 section 3.4.3

The shape of the XML affects the mapping. EmployeeContracts contains employees, repeating contracts, and repeating skills. Element-centric XML stores properties in child elements; attribute-centric XML stores them as attributes. Attributes may suit simple values, but repeating or ordered complex nodes require elements. section 3.4.1

A safer storage choice

When the employee’s contract and skill details must be exchanged as one document, store the native XML in an Employees.PreviousContracts column instead of shredding and rebuilding it. Extract only values needed for relational keys or columns, such as EmployeeID, name, and date of birth. In the demonstrated case, targeted XQuery extraction took 33 ms. section 3.4.3

Choose the approach deliberately:

  • Shred XML when relational querying and normalized relationships are the actual requirement. section 3.4.1
  • Store XML natively when the document is exchanged or retrieved as a whole. section 3.4.3
  • Use XQuery value() for selected nodes; provide a singleton node index, and prefix attribute names with @. section 3.4.3

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Explains nested mappings, normalization, table design, and OPENXML() implementation, then contrasts them with native XML storage.
Examples
Demonstrates employee contracts, repeating skills, normalized SQL tables, OPENXML(), and a PreviousContracts XML column.
What it assumes
Assumes basic XML and SQL knowledge while introducing normalization, element-versus-attribute mapping, and singleton extraction.
What you can do after
Apply XML shredding with SQL Server tables and OPENXML(), or extract selected fields with XQuery value().
How it connects
Connects XML shredding with XML, normalization, relational modeling, XQuery, XPath, and OPENXML().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.