1

I need to get data from xml file

    <?xml version="1.0"?>
    <xml>
    <User>
     <Agent>
      <id>cr4523</id>
     </Agent>
     <Time>
        <Time_Main>2-3pm</Time_Main>
        <Day>Mon</Day>
        <Time_Main>3-4pm</Time_Main>
        <Day>Mon</Day>
        <Time_Main>10-11am</Time_Main>
        <Day>Tue</Day>
      </Time>
     </User>
     </xml>

My problem is that a: not sure if my xml file is correctly formatted and b: the jquery I am using compressess all the data together, albiet in 'Time_Main' sections and 'Day' sections.

What I require is for each Time_Main and Day I need to call a simple function.

The jquery I am using is -

    $(html).find('Time').each(function(){
        var day=$(this).find('Day').text();
    var time_main=$(this).find('Time_Main').text();
    });

1 Answer 1

2

First thing, formatting is correct, but structuring not (I assume that Time/Day pairs are to be chosen as single entity). I'll do then:

 <?xml version="1.0"?>
<xml>
<User>
  <Agent>
     <id>cr4523</id>
  </Agent>
  <Time>
     <Time_Main>2-3pm</Time_Main>
     <Day>Mon</Day>
  </Time>
  <Time>
     <Time_Main>3-4pm</Time_Main>
     <Day>Mon</Day>
  </Time>
 </User>
 </xml>

From this you can loop through all the "Time" tags and retrieve Time_Main and Day.

$(html).find("Time").each(
        function (i,e)
        {
            console.log("New time tag...");
            console.log($(e).find("time_main").text());
            console.log($(e).find("day").text());
        }

        );

If you still need a single Time tag, wrap Time_main/Day couples in another tag:

<Time>
   <TimeGroup>
     <Time_Main>2-3pm</Time_Main>
     <Day>Mon</Day>
  </TimeGroup>
  <TimeGroup>
     <Time_Main>3-4pm</Time_Main>
     <Day>Mon</Day>
  </TimeGroup>
 </Time>

$(html).find("Time TimeGroup").each(
        function (i,e)
        {
            console.log("New time tag...");
            console.log($(e).find("time_main").text());
            console.log($(e).find("day").text());
        }

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

2 Comments

Thanks - this seems to make the data easier to run through even without looping.
Yes, you had the data flat becaus data was flat indeed... if my assumption was right, and time/data go in pairs, this is the best and easiest way to deal with the scenario

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.