【问题标题】:T-SQL XML: <eof> encountered when trying to query child nodes by wildcardT-SQL XML:尝试通过通配符查询子节点时遇到 <eof>
【发布时间】:2023-03-25 01:08:01
【问题描述】:

我们有一个内部软件可以处理松散定义的 XML 文件。我正在尝试从 T-SQL 中的此步骤中提取子节点。我能够提取父节点,但是每当我查询子节点时,我都会收到 语法错误。

XML 文件大致如下所示:

<?xml version="1.0"?>
<root>
  <steps>
    <step>
      <steptypeX attribute="somevalue">
        <child1>Value</child1>
        <child2>Value</child2>
      </steptypeX>
    </step>
  </steps>
</root>  

我正在使用以下 T-SQL:

select
doc.col.query('/child*') --If I use '.' or '*' here I can get the children as XML, but I want the values contained within the nodes on separate rows
from @xmldoc.nodes('/root/steps/step/steptypeX') doc(col)
where doc.col.value('@attribute', 'nvarchar(max)') = 'somevalue'

我收到的错误信息不清楚:

XQuery [query()]: Syntax error near '<eof>'  

据我所知,节点确实存在,并且我没有留下任何带有斜杠的 XQuery 指令。我真的不知道我在这里做错了什么。

【问题讨论】:

  • 您需要从您的 xml 中删除这一行 - &lt;?xml version="1.0"?&gt;。删除该行后,您的查询在我的系统中完美运行。
  • @KrishnrajRana 我刚刚尝试过,但它对我不起作用 - 无论是否使用 XML 声明,仍然会出现相同的 错误

标签: sql-server xml tsql nodes


【解决方案1】:

如果我正确理解您的意图,您可以使用child::*

DECLARE @xmldoc XML =
N'<?xml version="1.0"?>
<root>
  <steps>
    <step>
      <steptypeX attribute="somevalue">
        <child1>Value</child1>
        <child2>Value</child2>
      </steptypeX>
    </step>
  </steps>
  </root>';

SELECT
   doc.col.value('text()[1]', 'nvarchar(max)')
FROM @xmldoc.nodes('/root/steps/step/steptypeX/child::*') doc(col)
WHERE doc.col.value('../@attribute', 'nvarchar(max)') = 'somevalue';

LiveDemo

【讨论】:

  • 这似乎是我想要的!我真的不明白为什么我必须在 nodes() 函数中使用 /child:: 指令并返回 WHERE 子句,而不是找到父节点并选择子节点
  • @Gargravarr 关键是您来自/root/steps/step/steptypeX/ 的子元素具有不同的名称(child1 和 child2)。使用 child::* 您可以选择它们。但是在层次结构中您更深一步,因此您需要返回父节点以验证属性值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多