Can't get data from XML file

Viewed 218

I have an issue when i try to get data from xml file by D3JS. I can not match any data from xml file when I use a command from d3js. The following is my problem in detail: 1. command of d3. 2. results. 3. contain of my xml file.

d3.xml('files/d3.xml').then(function(data){
alert(JSON.stringify(data));
});

and results:

{"location":null}

this is my d3.xml file:

<?xml version="1.0" encoding="utf-8"?>
<data>
  <row>
    <loc>https://tuyetson.vn</loc>
    <priority>1.0</priority>
    <changefreq>daily</changefreq>
    <lastmod>2019-12-01</lastmod>
  </row>
  <row>
    <loc>https://tuyetson.vn/linh-vuc/linh-kien-may-in</loc>
    <priority>0.9</priority>
    <changefreq>daily</changefreq>
    <lastmod>2019-12-01</lastmod>
  </row>
  </data>

I hope someone can help me. Thanks you very much!

2 Answers

There is nothing wrong with the result you see, which has nothing to do with D3 by the way.

Internally, d3.xml uses DOMParser to parse the XML, creating a Document. Here it is, using your XML:

const xml = `<?xml version="1.0" encoding="utf-8"?>
<data>
  <row>
    <loc>https://tuyetson.vn</loc>
    <priority>1.0</priority>
    <changefreq>daily</changefreq>
    <lastmod>2019-12-01</lastmod>
  </row>
  <row>
    <loc>https://tuyetson.vn/linh-vuc/linh-kien-may-in</loc>
    <priority>0.9</priority>
    <changefreq>daily</changefreq>
    <lastmod>2019-12-01</lastmod>
  </row>
  </data>`;

const data = (new DOMParser).parseFromString(xml, "image/svg+xml");

console.log(data);

(Have a look at your browser's console, not the snippet one)

Then, you tried to use JSON.stringify with a document, and that obviously won't work:

const xml = `<?xml version="1.0" encoding="utf-8"?>
<data>
  <row>
    <loc>https://tuyetson.vn</loc>
    <priority>1.0</priority>
    <changefreq>daily</changefreq>
    <lastmod>2019-12-01</lastmod>
  </row>
  <row>
    <loc>https://tuyetson.vn/linh-vuc/linh-kien-may-in</loc>
    <priority>0.9</priority>
    <changefreq>daily</changefreq>
    <lastmod>2019-12-01</lastmod>
  </row>
  </data>`;

const data = (new DOMParser).parseFromString(xml, "image/svg+xml");

console.log(JSON.stringify(data)) 

If you (for whatever reason) want to stringify the DOM tree you cannot just pass it directly to JSON.stringify.

@Gerardo Furtado, thanks you so much for your explaination. After I had done what was suggested by you, I am not sure but i identified the results get from xml has a kind that likes a HTML construct. So i used some D3' normal methods, as a result it worked. the following is my code:

d3.xml('files/d3.xml').then(function(xml){
    //get data tag contain
    var a = d3.select(xml.documentElement);
    //get row tag contain
    var b = a.selectAll('row');
    //get and show lastmod contain
    console.log(b.select('lastmod').text());
});

the result is:

2019-12-01

I have not tested in detail, but perhaphs, I know what will I get from xml. Thanks you so much again @Gerardo Furtado

Related