0

I need a way to search through an XML String and return an array containing the "record" elements that meet multiple search criteria.

The structure is this:

  <record>
     <project_name>Deploy Document Management</project_name>
     <project_phase>Design</porject_phase>
     <status>Not Started</status>
     <priority>Medium</priority>
  </record>
  <record>
     <project_name>Do Something Else</project_name>
     <project_phase>Design</porject_phase>
     <status>Not Started</status>
     <priority>Medium</priority>   
  </record>

If I wanted to return an array of "records" where status="Not Started" and priority = "Medium".... how would I do so using javascript or JQuery?

To be clear, I need the whole record for each record that matches the criteria.

Thanks in advance.

0

1 Answer 1

1

A good start would be to parse the XML, for example with jQuery.parseXML()

You can then acces the DOM of the returned document as you usually would

Example:

var xml = '<xml><record><project_name>Deploy Document Management</project_name><project_phase>Design</project_phase><status>Not Started</status><priority>Medium</priority></record><record><project_name>Do Something Else</project_name><project_phase>Design</project_phase><status>Not Started</status><priority>Low</priority></record></xml>'

var xmlDoc = $.parseXML(xml)
var $xml = $(xmlDoc)
var $records = $xml.find("record").filter(function() {
  return $(this).find("status").text() == "Not Started" && 
    $(this).find("priority").text() == "Medium"
});

// $records already holds all Elements as an Array, but you cold get the texts like this:
var records = []
$records.each(function() {
  // do your thing
  records.push($(this).text())
})

document.write(JSON.stringify(records))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note that you have a typo in your original XML project_phase

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect... exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.