在Node.js中解析XML
问题描述:
我正在研究Node.js应用程序。我需要能够解析Sitemap.xml文件。目前,我有一个文件,网站地图,看起来像这样:在Node.js中解析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;
}
我不知道如何阅读和分析,虽然在世界上的节点XML。
有Node.js的无数的模块在那里的任何东西。我觉得XML解析已经实现了100次......(顺便说一句:'class'关键字是JS中全新的;确保你所支持的环境;请参阅:https://developer.mozilla.org/en-美国/ docs/Web/JavaScript /参考/语句/类) – feeela
可能的重复:[用于XML解析的最佳节点模块](http://*.com/questions/14890655/the-best-node-module-for -xml-解析) – feeela