【问题标题】:How do I get multiple XML children inside a single parent node instead of repeating the parent node for each child?如何在单个父节点中获取多个 XML 子节点,而不是为每个子节点重复父节点?
【发布时间】:2010-01-30 02:44:47
【问题描述】:

我正在尝试使用 FOR XML 从 SQL Server 2008 为 HL7 CDA 文档生成有效的 XML。我在一个节点内获取多个子节点而不是为每个子节点重复该节点的语法有问题。

/* Expected output:
<!-- 
********************************************************
  Past Medical History section
********************************************************
-->
    <component>
        <section>
            <code code="10153-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>
            <title>Past Medical History</title>
            <text>
                <list>
                    <item>COPD - 1998</item>
                    <item>Dehydration: 2001</item>
                    <item>Myocardial infarction: 2003</item>
                </list>
            </text>
        </section>
    </component>
*/

SELECT      '
   ********************************************************
     Past Medical History section
   ********************************************************
   ' As "comment()",
            '10153-2' AS [section/code/@code], 
            '2.16.840.1.113883.6.1' AS [section/code/@codeSystem], 
            'LOINC' AS [section/code/@codeSystemName], 
            'Past Medical History' AS [section/title],
            (SELECT     [Incident] + ' - ' + [IncidentYear] as [item]
             FROM       [tblSummaryPastMedicalHistory] AS PMH
             WHERE      ([PMH].[Incident] IS NOT NULL) 
                               AND      ([PMH].[PtUnitNum] = [PatientEncounter].[PtUnitNum])
             FOR XML PATH('list'), TYPE
            ) as [section/text]
FROM         tblPatientEncounter AS PatientEncounter
WHERE     (PatientEncounterNumber = 54)
FOR XML PATH('component'), TYPE

而不是得到

<text>
  <list>
    <item>blah</item>
    <item>blah2</item>
  </list>
</text> 

从预期的输出结构,我得到:

<text>
  <list>
    <item>blah</item>
  </list>
  <list>
    <item>blah2</item>
  </list>
</text> 

谁能解释一下如何格式化 FOR XML 以获取节点内的多个子节点?

【问题讨论】:

  • 这个问题是针对sql查询的,所以你应该删除xml标签

标签: sql-server xml


【解决方案1】:

想通了……

代替:

FOR XML PATH('list'), TYPE) as [section/text] 

改为:

FOR XML PATH(''), TYPE) as [list/section/text] 

希望这对将来的其他人有所帮助。

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多