SQL 2016 - 将XML转换为Json

时间:2017-08-17 07:11:09

标签: sql-server json xml tsql sql-server-2016

我正在尝试在SQL2016中使用FOR JSON PATH将XML列转换为Json但我遇到了一些问题。给出以下XML(请注意,某些Product元素可能包含Product列表):

  <Request>
    <SelectedProducts>
      <Product id="D04C01S01" level="1" />
      <Product id="158796" level="1" />
      <Product id="7464" level="2">
        <Product id="115561" level="3" />
      </Product>
      <Product id="907" level="2">
        <Product id="12166" level="3" />
        <Product id="33093" level="3" />
        <Product id="33094" level="3" />
        <Product id="28409" level="3" />
      </Product>
      <Product id="3123" level="2">
        <Product id="38538" level="3" />
        <Product id="37221" level="3" />
      </Product>
    </SelectedProducts>    
  </Request>

我可以在SQL上运行以下语句(其中@xml是上面的XML):

SELECT 
     d.value('./@id', 'varchar(50)') AS 'Id'
    ,d.value('./@level', 'int') AS 'Level'
    ,(SELECT 
        --f.value('../@id', 'varchar(50)') AS 'ParentId'
        f.value('./@id', 'varchar(50)') AS 'Id'
        ,f.value('./@level', 'int') AS 'Level'
        --FROM @xml.nodes('/Request/SelectedProducts/Product[@id="3123"]/Product') AS e(f)          
        FROM @xml.nodes('/Request/SelectedProducts/Product/Product') AS e(f)            
        FOR JSON PATH) 'Product'
    FROM @xml.nodes('/Request/SelectedProducts/Product') AS c(d)
    FOR JSON PATH

它生成的Json是这样的:

[{"Id":"D04C01S01", 
  "Level":2,
  "Product":[{"Id":"115561", "Level":3 }, {"Id":"12166","Level":3 }, { Id":"33093", "Level":3 }, {"Id":"33094","Level":3 }, {"Id":"28409","Level":3},
{"Id":"38538","Level":3},{"Id":"37221","Level":3 }]},

{"Id":"158796", 
  "Level":3,
  "Product":[{"Id":"115561", "Level":3 }, {"Id":"12166","Level":3 }, { Id":"33093", "Level":3 }, {"Id":"33094","Level":3 }, {"Id":"28409","Level":3},
{"Id":"38538","Level":3},{"Id":"37221","Level":3 }]...

您可以看到的问题是,在Json中生成的所有元素都以所有产品结束,无论其父关系如何。

我想我错过了WHERE子句,我会检查它属于父节点,但我无法弄清楚如何。

我尝试添加节点Product [@ id =“3123”](请参阅注释行),但我需要将“3123”替换为实际的父ID,我不知道该怎么做。

另一种选择是实际保存父ID(请参阅注释行ParentId),然后在结果中使用JSON_MODIFY删除不匹配的元素,但我也没有成功。

有没有人对如何解决这个问题有任何想法?或者我还能做些什么?

- 编辑 这是我期待的Json:

[{"Request": 
[{"Id":"D04C01S01","Level":1 }, 
{"Id":"158796","Level":1},
{"Id":"7464","Level":2,"Product":[{"Id":"115561","Level":3}]},
{"Id":"907","Level":2,"Product":[{"Id":"12166","Level":3},{"Id":"33093","Level":3},{"Id":"33094","Level":3},{"Id":"28409","Level":3}]},
{"Id":"3123","Level":2,"Product":[{"Id":"38538","Level":3},{"Id":"37221","Level":3}]}]}]

您可以假设,如果Level = 1,则不会有Product子级别,如果Level = 2,则会有Product子级别。

谢谢

4 个答案:

答案 0 :(得分:2)

内部节点集上的XPath正在从XML中选择所有节点,而不仅仅是外部节点的子节点。

(我没有SQL2016的副本,但是这样的东西应该有效。)

SELECT 
    d.value('./@id', 'varchar(50)') AS 'Id'
    ,d.value('./@level', 'int') AS 'Level'
    ,(SELECT 
        f.value('./@id', 'varchar(50)') AS 'Id'
        ,f.value('./@level', 'int') AS 'Level'
        FROM c.d.nodes('./Product') AS e(f)            
        FOR JSON PATH) 'Product'
FROM @xml.nodes('/Request/SelectedProducts/Product') AS c(d)
FOR JSON PATH

答案 1 :(得分:0)

作为部分解决方案,这样您就可以从XML输入中获得hierarhy邻接对。然后你需要再次递归将它包装到JSON我相信。

for(String storageVolumePath:storageVolumePaths) {
    File androidDataFolder = new File((String) storageVolumePath + "/Android/data/");
    if (androidDataFolder.exists()) {
        File[] filesList = androidDataFolder.listFiles();
        if (filesList != null) {
            for (File file : filesList) {
                if (file.isDirectory()) {
                    file = new File(file.getAbsolutePath() + "/cache/");
                    if(file.exists()) {
                        try {
                            deleteFile(file);
                        }catch (Exception e ){}
                    }
                }
            }
        }
    }
}

答案 2 :(得分:0)

我不太了解level值。 level="1"的产品似乎没有任何子产品。在XML中的同一(层次)级别,有level="2"个产品,包含嵌套的level="3"产品。这对所有情况都有效吗?

如果是这样,您需要使用OUTER APPLY分两步查询XML:

DECLARE @xml XML=
N'<Request>
  <SelectedProducts>
    <Product id="D04C01S01" level="1" />
    <Product id="158796" level="1" />
    <Product id="7464" level="2">
      <Product id="115561" level="3" />
    </Product>
    <Product id="907" level="2">
      <Product id="12166" level="3" />
      <Product id="33093" level="3" />
      <Product id="33094" level="3" />
      <Product id="28409" level="3" />
    </Product>
    <Product id="3123" level="2">
      <Product id="38538" level="3" />
      <Product id="37221" level="3" />
    </Product>
  </SelectedProducts>
</Request>';

SELECT p1.value(N'@id','nvarchar(max)') AS P1_id
      ,p1.value(N'@level','int') AS P1_level
      ,p2.value(N'@id','nvarchar(max)') AS P2_id
      ,p2.value(N'@level','int') AS P2_level
FROM @xml.nodes(N'/Request/SelectedProducts/Product') AS A(p1)
OUTER APPLY A.p1.nodes(N'Product') AS B(p2);

结果

+-----------+----------+--------+----------+
| P1_id     | P1_level | P2_id  | P2_level |
+-----------+----------+--------+----------+
| D04C01S01 | 1        | NULL   | NULL     |
+-----------+----------+--------+----------+
| 158796    | 1        | NULL   | NULL     |
+-----------+----------+--------+----------+
| 7464      | 2        | 115561 | 3        |
+-----------+----------+--------+----------+
| 907       | 2        | 12166  | 3        |
+-----------+----------+--------+----------+
| 907       | 2        | 33093  | 3        |
+-----------+----------+--------+----------+
| 907       | 2        | 33094  | 3        |
+-----------+----------+--------+----------+
| 907       | 2        | 28409  | 3        |
+-----------+----------+--------+----------+
| 3123      | 2        | 38538  | 3        |
+-----------+----------+--------+----------+
| 3123      | 2        | 37221  | 3        |
+-----------+----------+--------+----------+

p1位于<SelectedProducts>正下方的所有产品,而p2是另一产品下方的嵌套产品。

如果没有您可能需要的JSON示例,我在这里无法帮助您,但这应该会让您走上某种轨道......

答案 3 :(得分:-1)

您可以尝试使用C#代码转换数据库中的所有记录,如下所示:

// read record from your table and for column colname
string yourColnameValueXmlIn = '' // assign here your value

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(yourColnameValueXml );
string yourColnameValueJSONOut = JsonConvert.SerializeXmlNode(doc);

// assign your new value in json to column in record
// save your updated record