Link to home
Start Free TrialLog in
Avatar of RayT
RayTFlag for United States of America

asked on

Query XML Using JQuery or Javascript

Using either JQuery or JavaScript I want to open a file call AccessCodes.xml.  I want to open AccessCodes.xml and query the file and return the Root value for a given Password.  How can I do this?


For example if the given password is 456 it should return def


Also, if the given password is 482 it should return null


<Folders>
    <Folder>
        <Password>123</Password>
        <Root>abc</Root>
    </Folder>

    <Folder>
        <Password>456</Password>
        <Root>def</Root>
    </Folder>

    <Folder>
        <Password>789</Password>
        <Root>ghi</Root>
    </Folder>
</Folders>


Avatar of ste5an
ste5an
Flag of Germany image

Just a comment:

Storing passwords is a sever security issue. Stored salted hashes instead. See Plain Text Offenders.

When there is a use-case to store it, then store it encrypted.
Like this

https://jsfiddle.net/mplungjan/4fwxhszv/

const findRoot = password => $(xml).find("Password")
  .filter(
    function() { return this.textContent.trim() === password }
    ).next().text();
console.log(findRoot("456"))
console.log(findRoot("482"))

Open in new window

Hi,

have a look here:
https://codepen.io/jeschor/pen/jOGgNvB

let xmlString = "<Folders><Folder><Password>123</Password><Root>abc</Root></Folder><Folder><Password>456</Password><Root>def</Root></Folder><Folder><Password>789</Password><Root>ghi</Root></Folder></Folders>";

function findInXml()
{
  var xmlDoc = $.parseXML( xmlString );
  $xml = $( xmlDoc );
  var found = false;
  $xml.find("Folder").each(function() {
    var currentFolder = $(this);
    $rt = currentFolder.find("Password").text() == $('#queryValue').val() ? $(this).find( "Password" ) : false;
  if ($rt)
    {
      found = true;
      $("#result").val($rt.parent().children("Root").text());
    }
  });
  if (found == false)
    {
      $("#result").val("Not Found");
    }
}

Open in new window

Avatar of RayT

ASKER

This one works.  One thing.  How do I load a string (xml) from the XML file?

const xml = `<Folders>
    <Folder>
        <Password>123</Password>
        <Root>abc</Root>
    </Folder>

    <Folder>
        <Password>456</Password>
        <Root>def</Root>
    </Folder>

    <Folder>
        <Password>789</Password>
        <Root>ghi</Root>
    </Folder>
</Folders>`

const findRoot = password => $(xml).find("Password")
  .filter(
    function() { return this.textContent.trim() === password }
    ).next().text();
console.log(findRoot("456"))
console.log(findRoot("482"))
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RayT

ASKER

Thanks!