Sort all attributes of XML in SQL query using XQue

2020-04-07 12:34发布

How can get the XML with sorted attributes using XQuery in SQL?

for example for this XML:

<root><book b='' c='' a=''/></root>

must return:

<root><book a='' b='' c=''/></root>

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-04-07 12:43

Attributes are unordered in XML, so the document is considered the same whichever order the attributes are printed out in. XQuery certainly has no way to change the order of attributes, and I doubt SQL XML does either.

查看更多
forever°为你锁心
3楼-- · 2020-04-07 12:43

Beyond Mikael Eriksson's helpful answer that SQL Server will not preserve XML attribute ordering, and Michael Kay's special accommodation in Saxon for alphabetically serialization attributes by name, future readers should be warned that the XML Recommendation says that the the order of XML attributes is insignificant:

Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.

Therefore, XML tools generally do not care about attribute ordering, and unless you are concerned with XML normalization/canonicalization1, neither should you. Without provision for attribute ordering in the XML Recommendation, achieving an ordering by leveraging special mechanisms such as saxon:attribute-order will likely prove to be only a temporary, localized success as the XML ecosystem will not guarantee any ordering as your XML passes through tools and toolchains through its life cycle.

1For those rare circumstances, see the section on attribute processing in the XML Normalization Recommendation or the Canonical XML Recommendation.

查看更多
祖国的老花朵
4楼-- · 2020-04-07 12:44

From Limitations of the xml Data Type.

The order of attributes in an XML instance is not preserved. When you query the XML instance stored in the xml type column, the order of attributes in the resulting XML may be different from the original XML instance.

So even if you could figure out a way of sorting the attributes, you can not trust that the XML data type in SQL Server will preserve the order you want.

查看更多
Ridiculous、
5楼-- · 2020-04-07 13:05

Although the order of attributes has no semantic significance, one of the design goals of XML is to be human-readable, so it is not entirely unreasonable to try to generate lexical XML in which the order of attributes is consistent and reflects user expectations: for example <point x="2" y="5" z="7"/> is easier on the eye than <point z="7" x="2" y="5"/>. The Saxon serializer therefore has an option saxon:attribute-order that allows the ordering of attributes in the output XML to be controlled: see http://www.saxonica.com/documentation/index.html#!extensions/output-extras/serialization-parameters

查看更多
登录 后发表回答