Select on multiple criteria with XPath

后端 未结 3 1522
时光取名叫无心
时光取名叫无心 2020-12-17 08:46

I have an XML document which looks something like this:


 
  MENSWEAR 
  

        
3条回答
  •  执念已碎
    2020-12-17 09:04

    Union
    In order to get both nodes you need to use union operator - |

    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
    

    Filter by sub-nodes values
    In order to filter node based on its sub-nodes values you need to place all conditions in same brackets [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']
    

    A C# union example:

    [Test]
    public void UnionExample()
    {
        string xml =
            @"
                
                    MENSWEAR 
                    ACCESSORIES 
                    BELTS 
                    AWESOME_BELTS
                
              ";
    
        XDocument xDocument = XDocument.Parse(xml);
        IEnumerable selectedElements =
            xDocument.XPathSelectElements(
                    "/meadinkent/record/comp_div | /meadinkent/record/sty_ret_type");
    
        Assert.That(selectedElements.Count(), Is.EqualTo(2));
    }
    

    A C# filter by sub-nodes example:

    [Test]
    public void FilterExample()
    {
        string xml =
            @"
                
                    MENSWEAR 
                    ACCESSORIES 
                    BELTS 
                    AWESOME_BELTS
                
              ";
    
        XDocument xDocument = XDocument.Parse(xml);
        IEnumerable 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"));
    }
    

提交回复
热议问题