简体   繁体   English

使用 SQL 服务器 2016 解析 XML

[英]Parse XML using SQL Server 2016

I'm trying to clean up some SQL code.我正在尝试清理一些 SQL 代码。 Currently I have an XML like:目前我有一个 XML 像:

DECLARE @xml xml = N'<PubmedArticleSet>
  <PubmedArticle>
    <MedlineCitation Status="MEDLINE" Owner="NLM">           
      <ArticleIdList>           
        <ArticleId IdType="pii">0092-8674(92)90516-F</ArticleId>
        <ArticleId IdType="pubmed">1423608</ArticleId>
        <ArticleId IdType="doi">10.1016/0092-8674(92)90516-f</ArticleId>
      </ArticleIdList>
    </PubmedData>
  </PubmedArticle>
</PubmedArticleSet>'

And I need to get the value of the ArticleId with the attribute of我需要使用属性获取ArticleId的值

    IdType ="pubmed"

I would like something like and XQUERY method that could:我想要类似XQUERY方法的东西,它可以:

DECLARE @PMID NVARCHAR(15)
SET @PMID =  @xml.value('(//PubmedData/ArticleIdList/ArticleId/@IdType)[1]', 'varchar(15)' ) 

But that pulls the IdType "pii" of the first node.但这会拉动第一个节点的 IdType “pii”。 And

SET @PMID =  @xml.value('(//PubmedData/ArticleIdList/ArticleId/@IdType = "pubmed")[1]', 'varchar(15)' ) 

Brings back true.带回真实。

Is there a way to filter based upon "pubmed" and then get the number 1423608?有没有办法根据“pubmed”进行过滤,然后得到数字 1423608? So @PMID would then be equal to 1423608.所以@PMID将等于 1423608。

Your provided XML is not well-formed.您提供的 XML 格式不正确。 There are several tags missing, hope this is corrected here:缺少几个标签,希望在这里更正:

DECLARE @xml xml = N'<PubmedArticleSet>
  <PubmedArticle>
  <PubmedData>
    <MedlineCitation Status="MEDLINE" Owner="NLM">           
      <ArticleIdList>           
        <ArticleId IdType="pii">0092-8674(92)90516-F</ArticleId>
        <ArticleId IdType="pubmed">1423608</ArticleId>
        <ArticleId IdType="doi">10.1016/0092-8674(92)90516-f</ArticleId>
      </ArticleIdList>
      </MedlineCitation>
    </PubmedData>
  </PubmedArticle>
</PubmedArticleSet>';

DECLARE @IdToFind VARCHAR(100)='pubmed';

SELECT @xml.value('(/PubmedArticleSet
                    /PubmedArticle
                    /PubmedData
                    /MedlineCitation
                    /ArticleIdList
                    /ArticleId[@IdType=sql:variable("@IdToFind")]
                    /text())[1]','int');

The idea in short:简而言之:

  • We can use variable to get this a bit more generic.我们可以使用变量来使其更通用。
  • We dive into the XML, down to the <ArticleIdList> and我们深入研究 XML,一直到<ArticleIdList>
  • find the one <ArticleId> where the attribute IdType equals the given value.找到属性IdType等于给定值的<ArticleId>
  • From there we return the text() .从那里我们返回text()

You would get the same with a simple deep search too:您也可以通过简单的深度搜索得到相同的结果:

SELECT @xml.value('(//ArticleId[@IdType=sql:variable("@IdToFind")]/text())[1]','int');

But the general advise is: Be as specific as possible.但一般建议是:尽可能具体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM