Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select all elements in Xml document with specific inner fields

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading