Parsing XML in Node.js
我正在开发Node.js应用。我需要能够解析Sitemap.xml文件。当前,我有一个文件站点地图,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?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> |
我正在尝试解析此xml文件并将其加载到我的JavaScript类中,如下所示:
1 2 3 4 5 6 7 8 9 10 11 | class SiteUrl { constructor() { this.loc = ''; this.lastMod = null; this.changeFreq = 'never'; } static loadFromSitemap(sitemapPath) { } } |
来自C#背景,我知道我可以这样做:
1 2 3 4 5 6 7 8 9 10 11 12 | 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; } |
我不确定如何在Node世界中读取和解析Xml。
您可以尝试以下npm模块:
https://github.com/Leonidas-from-XIV/node-xml2js
完成工作并构建一个不错的JavaScript对象