【发布时间】:2015-12-25 17:53:22
【问题描述】:
我正在开发一个 Node.js 应用程序。我需要能够解析 Sitemap.xml 文件。目前,我有一个文件站点地图,如下所示:
<?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 类中,如下所示:
class SiteUrl {
constructor() {
this.loc = '';
this.lastMod = null;
this.changeFreq = 'never';
}
static loadFromSitemap(sitemapPath) {
}
}
来自 C# 背景,我知道我可以这样做:
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。
【问题讨论】:
-
有无数的 Node.js 模块可以满足任何需求。我觉得 XML 解析已经实现了 100 次......(顺便说一句:
class关键字在 JS 中是全新的;确保您所处的环境支持它;请参阅:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
标签: javascript xml node.js