[英]Parsing XML in Node.js
I am working on a Node.js app.我正在开发一个 Node.js 应用程序。 I need to be able to parse a Sitemap.xml file.我需要能够解析 Sitemap.xml 文件。 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:我正在尝试解析此 xml 文件并将其加载到我的 JavaScript 类中,如下所示:
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:来自 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;
}
I'm not sure how to read and parse Xml in the Node world though.不过,我不确定如何在 Node 世界中读取和解析 Xml。
You may try this npm module:你可以试试这个 npm 模块:
https://github.com/Leonidas-from-XIV/node-xml2js https://github.com/Leonidas-from-XIV/node-xml2js
It gets the job done and builds a nice JavaScript object它完成了工作并构建了一个不错的 JavaScript 对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.