代码之家  ›  专栏  ›  技术社区  ›  SaSH_17

从SQL Server中的XML列创建XML结构

  •  0
  • SaSH_17  · 技术社区  · 8 年前

    我有一张超过100万行的桌子。在这个表中,我有一列包含大型XML文件(数据类型XML)。现在,我必须生成/查找所有这些XML文件的结构。

    XML文件的结构通常是不同的,所以并不总是相同的。是否有可能为所有这些行生成一个xsd文件,以找出结构或评估XML文件中的标记?

    您是否有任何想法/流程来获取所有这些XML文件的结构?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Gottfried Lesigang    8 年前

    不,没有一般的方法,至少我不知道… 假设两个XML看起来是相同的,但是其中一个有一个子元素,而另一个缺少该子元素。这可能是相同的模式,或者不是…

    通过以下方法,您可以检索到一些 元数据 . 把这个写在边桌上,试着用 GROUP BY 找到你的 XML系列

    DECLARE @tbl TABLE(ID INT IDENTITY, ShortDescr VARCHAR(100), YourXML XML);
    INSERT INTO @tbl VALUES
     ('root and test', N'<root><test/></root>')
    ,('root and test and more', N'<root><test/><a /><b /></root>')
    ,('blah and test', N'<blah><test/></blah>')
    ,('no root (blah and blub)', N'<blah></blah><blub />')
    ,('no content', NULL)
    ;
    
    SELECT t.ID
          ,t.ShortDescr
          ,CASE ISNULL(t.YourXML.value('count(/*)','int'),0)
                WHEN 1 THEN 'HasRoot'
                WHEN 0 THEN 'empty'
                ELSE 'Fragment' END AS XmlFormat
          ,t.YourXML.value('local-name((/*)[1])','nvarchar(max)') AS RootName 
          ,t.YourXML.value('local-name((/*[1]/*)[1])','nvarchar(max)') AS FirstChild
    FROM @tbl t;
    

    结果如下:

    +----+-------------------------+-----------+----------+------------+
    | ID | ShortDescr              | XmlFormat | RootName | FirstChild |
    +----+-------------------------+-----------+----------+------------+
    | 1  | root and test           | HasRoot   | root     | test       |
    +----+-------------------------+-----------+----------+------------+
    | 2  | root and test and more  | HasRoot   | root     | test       |
    +----+-------------------------+-----------+----------+------------+
    | 3  | blah and test           | HasRoot   | blah     | test       |
    +----+-------------------------+-----------+----------+------------+
    | 4  | no root (blah and blub) | Fragment  | blah     |            |
    +----+-------------------------+-----------+----------+------------+
    | 5  | no content              | empty     | NULL     | NULL       |
    +----+-------------------------+-----------+----------+------------+