Home > Back-end >  How to select all elements in Xml document with specific inner fields
How to select all elements in Xml document with specific inner fields

Time:01-11

For example I have xml:

<Cars>
    <Car>
        <Name>BMW</Name>
        <Color>Blue</Color>
    </Car>
    <Car>
        <Name>Mercedes</Name>
        <Color>Yellow</Color>
    </Car>
    <Car>
        <Name>Mercedes</Name>
        <Color>Blue</Color>
    </Car>
</Cars>

And I need to choose all cars with color Blue. Is there a way I can do it efficiently with selectors or/and loops?

CodePudding user response:

The :contains() selector and parent function of jQuery help for this goal.

The :contains() selector, selects all elements that contain the specified text. More information: https://api.jquery.com/contains-selector/#contains1

The .parent() method, gets the parent of each element in the current set of matched elements, optionally filtered by a selector. More information: https://api.jquery.com/parent/#parent-selector

In the following code objs contains two elements:

var objs = $('Car>Color:contains("Blue")').parent()
console.log(objs.eq(0).html())
console.log(objs.eq(1).html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<Cars>
    <Car>
        <Name>BMW</Name>
        <Color>Blue</Color>
    </Car>
    <Car>
        <Name>Mercedes</Name>
        <Color>Yellow</Color>
    </Car>
    <Car>
        <Name>Mercedes</Name>
        <Color>Blue</Color>
    </Car>
</Cars>

  •  Tags:  
  • Related