2015-09-28 69 views
-1

我正在研究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。

+0

有Node.js的無數的模塊在那裏的任何東西。我覺得XML解析已經實現了100次......(順便說一句:'class'關鍵字是JS中全新的;確保你所支持的環境;請參閱:https://developer.mozilla.org/en-美國/ docs/Web/JavaScript /參考/語句/類) – feeela

+1

可能的重複:[用於XML解析的最佳節點模塊](http://stackoverflow.com/questions/14890655/the-best-node-module-for -xml-解析) – feeela

回答