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

如何构建XQuery以根据某些标记和属性的存在来包含/排除行?

  •  0
  • jscharf  · 技术社区  · 16 年前

    <updateInvoice id="5" userId="7" /><fieldUpdate name="InvoiceDate" /><invoice /><update />
    
    <deleteInvoice id="5" userId="6" /><invoice /><delete />
    

    invoice userId='7' “,或”包含带有标记的所有行 delete

    我希望通过使用简单过滤器结构的组合来表示我想要包含或排除的行的标签和属性的组合,从而以编程方式实现这一点。

    enum FilterInclusion { Include, Exclude };
    
    public struct Filter
    {
        FilterInclusion Inclusion;
        string TagName;
        string? AttributeName;
        object? AttributeValue;
    }
    

    我应该并且可以将这个布尔逻辑编码到XPath本身中,还是我希望在输出的查询中有多个SELECT语句?我是XQuery的新手,非常感谢您的帮助。谢谢!

    1 回复  |  直到 16 年前
        1
  •  1
  •   Remus Rusanu    16 年前

    我不确定这是否是您要找的,但要过滤XML方法中的节点,您可以使用括号 [ ] 例如,选择元素 foo 但仅过滤具有该属性的那些 bar /foo[@bar] 。如果你想要那些具有该属性的 @bar 使用值5 /foo[@bar=5] 。如果要选择元素 孩子 元素 酒吧 /foo[bar] .

    declare @t table (x xml);
    insert into @t (x) values 
    (N'<foo bar="abc"/>');
    insert into @t (x) values 
    (N'<foo bar="5"/>');
    insert into @t (x) values 
    (N'<foo id="1"><bar id="2"/></foo>');
    select * from @t;
    
    select c.value(N'@bar', N'varchar(max)') 
    from @t cross apply x.nodes(N'/foo[@bar]') t(c)
    
    select c.value(N'@bar', N'varchar(max)') 
    from @t cross apply x.nodes(N'/foo[@bar=5]') t(c)
    select c.value(N'@id', N'int') 
    from @t cross apply x.nodes(N'/foo[bar]') t(c)
    

    我试图在您的帖子中展示XML片段上的示例,但这些示例太无结构,无法制作有用的示例。