5

Do I need to parse my xml to get the data from the xml to render in the html? I'm currently getting a local .xml file using http.get request and in console log its showing all the information that's in the xml file I think its just reading it.

Question is how to convert xml into json format in angular2?

I tried the console.log(data.title) but this is returning me as unidentified

getXml() {
   this.http.get('../../xmlConf/dashboard_journey.xml')
    .map(response => response.text())
    .subscribe(data => {
        if(data) {
            console.log('fetching your xml');
            console.log(data); // this shows me everything
        }
    });
}

xml

<xml>
<journey>
    <title>Click and Collect</title>
    <shortDesc>
        <short_desc_1>lorem</short_desc_1>
        <short_desc_2>lorem</short_desc_2>
    </shortDesc>
    <longDesc>
        lorem
    </longDesc>
    <imageName>
        <img src="/journey_images/clickandcollect.jpg" alt="Click and Collect"/>
    </imageName>
</journey>

Using the answer below

var parser = new DOMParser();
xmlData = parser.parseFromString(data, "application/xml");

console.log of the above code:

enter image description here

Currently doing for loop to iterate the parsed xml, however in my view its only giving me one object. ngFor only iterates objects that is in an array.

for (var i = 0; i <= newFormat.childNodes.length; i++) {
                this.title = newFormat.getElementsByTagName('title')[i].childNodes[0].nodeValue;
                this.desc = newFormat.getElementsByTagName('desc')[i].childNodes[0].nodeValue;
                console.log(this.title + ' = ' +  this.desc);
            }

view:

<li>{{ title }}</li>
2
  • What happens when you give, console.log(data[0].title) Commented Aug 4, 2016 at 11:33
  • if I do data[0] its only showing me < so I think I need to convert this xml into json. Commented Aug 4, 2016 at 11:36

1 Answer 1

2

You can use DOMParser

You simply pass your data variable to DOMParser then you can access elements by reference

Example

var parser = new DOMParser();
xmlData = parser.parseFromString(data, "application/xml");
Sign up to request clarification or add additional context in comments.

4 Comments

I console log xmlData and its giving me a json format, but xml stuff is nested inside #document and couldn't access the elements like title, longDesc when I do xmlData.title or longDesc
see my edit in my post above, that's still an xml not json fomat. Really want to avoid doing for each in each tag just to return it.
On my phone atm but try xmlData.getElementsByTagName("title")[0].childNodes[0].nodeValue;
yeah that's how I'm doing it atm see my for loop code in my original post above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.