-1

I am working on a Node.js app. I need to be able to parse a Sitemap.xml file. Currently, I have a file sitemap that looks like this:

<?xml version="1.0" encoding="utf-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

  <url>
    <loc>http://www.example.com</loc>
    <lastmod>2014-03-05</lastmod>
    <changefreq>monthly</changefreq>
  </url>

  <url>
    <loc>http://www.example.com/contact</loc>
    <lastmod>2014-03-05</lastmod>
    <changefreq>never</changefreq>
  </url>

  <url>
    <loc>http://www.example.com/about</loc>
    <lastmod>2015-03-01</lastmod>
    <changefreq>monthly</changefreq>
  </url>
</urlset>

I am trying to parse this xml file and load it into my JavaScript class, which looks like this:

class SiteUrl {
  constructor() {
    this.loc = '';
    this.lastMod = null;
    this.changeFreq = 'never';
  }

  static loadFromSitemap(sitemapPath) {

  }
}

Coming from a C# background, I know I could just do this:

public static List<SiteUrl> LoadFromSitemap(string sitemapPath)
{
  // Load the sitemap into memory
  XDocument sitemap = XDocument.Load(sitemapPath);

  // Get the posts from the sitemap.
  List<SiteUrl> posts = (from post in sitemap.Root.Elements(ns + "url")
                         where ((string)post.Element(ns + "loc"))
                         select new SiteUrl(post)).ToList();

  return posts;
}

I'm not sure how to read and parse Xml in the Node world though.

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134
  • There is a myriad of Node.js modules out there for anything. I feel like XML parsing was already implemented a 100 times… (BTW: the `class` keyword is brand new in JS; make sure the environment you are in supports that; see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class) – feeela Sep 28 '15 at 13:15
  • 1
    possible duplicate of: [The best node module for XML parsing](http://stackoverflow.com/questions/14890655/the-best-node-module-for-xml-parsing) – feeela Sep 28 '15 at 13:16

1 Answers1

1

You may try this npm module:

https://github.com/Leonidas-from-XIV/node-xml2js

It gets the job done and builds a nice JavaScript object

Lacrioque
  • 358
  • 7
  • 11