-1
 <students>
 <person>
  <name>Harry</name>
  <age>20</age>
  <city>Newyork</city>
 </person>
 <person>
  <name>Harry</name>
  <age>25</age>
  <city>California</city>
 </person>
 <person>
  <name>Ron</name>
  <age>22</age>
  <city>Florida</city>
 </person>
</students>

In the above xml, assuming I already know the values for name 'Harry' & age '20'. I would like to get the value of city using those two values as input. I'm trying to use jquery. Since two 'Harry's are there, I want to use one more value to get correct city. Assuming its an external xml file.

  • Is [this](https://stackoverflow.com/questions/5723009/xpath-query-for-finding-an-element-with-a-condition-which-matches-the-attribute) helpful? – raina77ow Aug 21 '23 at 07:23
  • 1
    Please visit the [help], take the [tour] to see what and [ask]. Do some research - [search SO for answers](https://www.google.com/search?q=javascript+parse+XML+site%3Astackoverflow.com). If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Aug 21 '23 at 07:43
  • let ele = document.querySelectorAll("person"); for(let i=0;i – Kangkan Lahkar Aug 21 '23 at 07:49

1 Answers1

0

You need to parse and filter/find the xml

const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, "application/xml");
// print the name of the root element or error message
const errorNode = doc.querySelector("parsererror");
if (errorNode) {
  console.log("error while parsing");
} else {
  const getCity = (name, age) => {
    const person = [...doc.querySelectorAll("person")].find(person => {
      return person.querySelector('name').textContent === name && person.querySelector('age').textContent === age
    });
    return person?.querySelector("city")?.textContent ?? 'not found'
  };


  console.log(getCity('Harry', '20'))
  console.log(getCity('Harry', '25'))
  console.log(getCity('Harry', '30'))

}
<script>
  const xmlString = `
 <students>
 <person>
  <name>Harry</name>
  <age>20</age>
  <city>Newyork</city>
 </person>
 <person>
  <name>Harry</name>
  <age>25</age>
  <city>California</city>
 </person>
 <person>
  <name>Ron</name>
  <age>22</age>
  <city>Florida</city>
 </person>
</students>`;
</script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236