使用 XPath 选择多个条件 [英] Select on multiple criteria with XPath

查看:42
本文介绍了使用 XPath 选择多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的 XML 文档:

I have an XML document which looks something like this:

<meadinkent>
 <record>
  <comp_div>MENSWEAR</comp_div> 
  <sty_ret_type>ACCESSORIES</sty_ret_type> 
  <sty_pdt_type>BELTS</sty_pdt_type> 
  <pdt_category>AWESOME_BELTS</pdt_category> 
  </record>
<medinkent>

我想使用 XPath 来选择匹配所有四个元素的节点,但我无法正确使用布尔语法.我正在尝试将其与前两个相匹配作为测试:

I want to useXPath to select nodes which match all four elements and I'm having trouble getting the boolean syntax right. I'm trying this to match the first two just as a test:

"/meadinkent/record/comp_div[.='" & comp_div & "'] and /meadinkent/record/sty_ret_type[.='" & sty_ret_type & "']"

哪个失败了,说没有返回任何节点.显然我很愚蠢 - 我做错了什么?

Which is failing, saying no nodes are returned. Obviously I'm being very stupid - what am I doing wrong?

干杯,毫安

推荐答案

联合
为了获得两个节点,您需要使用联合运算符 - |

例如,下一个查询将返回两种类型的节点 - comp_divsty_ret_type:

For example, the next query will return both type of nodes - comp_div and sty_ret_type:

/meadinkent/record/comp_div | /meadinkent/record/sty_ret_type

按子节点值过滤
为了根据其子节点值过滤节点,您需要将所有条件放在相同的括号中 [nodeA='value1' and nodeB='value2']

例如,下一个查询将返回其子节点与过滤器匹配的记录节点:

For example, the next query will return record nodes whose sub nodes match the filter:

/meadinkent/record[comp_div='MENSWEAR' and sty_ret_type='ACCESSORIES']

一个 C# 联合示例:

A C# union example:

[Test]
public void UnionExample()
{
    string xml =
        @"<meadinkent>
            <record>
                <comp_div>MENSWEAR</comp_div> 
                <sty_ret_type>ACCESSORIES</sty_ret_type> 
                <sty_pdt_type>BELTS</sty_pdt_type> 
                <pdt_category>AWESOME_BELTS</pdt_category>
            </record>
          </meadinkent>";

    XDocument xDocument = XDocument.Parse(xml);
    IEnumerable<XElement> selectedElements =
        xDocument.XPathSelectElements(
                "/meadinkent/record/comp_div | /meadinkent/record/sty_ret_type");

    Assert.That(selectedElements.Count(), Is.EqualTo(2));
}

按子节点的 C# 过滤器示例:

A C# filter by sub-nodes example:

[Test]
public void FilterExample()
{
    string xml =
        @"<meadinkent>
            <record>
                <comp_div>MENSWEAR</comp_div> 
                <sty_ret_type>ACCESSORIES</sty_ret_type> 
                <sty_pdt_type>BELTS</sty_pdt_type> 
                <pdt_category>AWESOME_BELTS</pdt_category>
            </record>
          </meadinkent>";

    XDocument xDocument = XDocument.Parse(xml);
    IEnumerable<XElement> selectedElements =
        xDocument.XPathSelectElements(
       "/meadinkent/record[comp_div='MENSWEAR' and sty_ret_type='ACCESSORIES']");

    Assert.That(selectedElements.Count(), Is.EqualTo(1));
    Assert.That(selectedElements.First().Name.LocalName, Is.EqualTo("record"));
}

这篇关于使用 XPath 选择多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆