Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
大數(shù)據(jù)項(xiàng)目開發(fā)過程中,ETL(Extract-Transform-Load)必不可少。即使目前 JSON 非常流行,開發(fā)人員也必定有機(jī)會(huì)面對(duì)遠(yuǎn)古系統(tǒng)的挑戰(zhàn),而 XML 格式的數(shù)據(jù)源作為經(jīng)典存在渾身上下散發(fā)著濃濃 old money 的味道。
因?yàn)橛?Newtonsoft.Json 這樣優(yōu)秀的 JSON 框架存在,開發(fā)人員可以很容易的對(duì) JSON 格式的字符串反序列化。但是 XML 格式的數(shù)據(jù)就沒有這么方便了:雖然 .NET 中內(nèi)置了對(duì) XML 序列化和反序列化的支持,但遇到需要對(duì)接外部數(shù)據(jù)時(shí)就不是很方便了。
從 XML 中提取目標(biāo)數(shù)據(jù)最高效,也最麻煩的方式是直接使用 XmlReader :
<employee xmlns="urn:empl-hire">
<ID>12365</ID>
<hire-date>2003-01-08</hire-date>
<title>Accountant</title>
</employee>
使用以下代碼對(duì)上述 hireDate.xml 文件讀取:
using (XmlReader reader = XmlReader.Create("hireDate.xml")) {
// Move to the hire-date element.
reader.MoveToContent();
reader.ReadToDescendant("hire-date");
// Return the hire-date as a DateTime object.
DateTime hireDate = reader.ReadElementContentAsDateTime();
Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6));
}
輸出:
Six Month Review Date: 7/8/2003 12:00:00 AM
在 .NET Framework 3.5 發(fā)布后的時(shí)間里,開發(fā)人員可以使用 XDocument 來生成和解析 XML 文檔,這要比 XmlReader 方便得多:
string str =
@"<?xml version=""1.0""?>
<!-- comment at the root level -->
<Root>
<Child>Content</Child>
</Root>";
XDocument doc = XDocument.Parse(str);
Console.WriteLine(doc.XPathSelectElement("//Child"));
輸出:
<Child>Content</Child>
但硬編碼的 XPath 并不方便調(diào)試,而且需要時(shí)刻關(guān)注空引用的問題。在 XML 格式復(fù)雜、項(xiàng)目工程比較大時(shí)使用起來也不方便。
在計(jì)算機(jī)科學(xué)中,可擴(kuò)展樣式表轉(zhuǎn)換語言(英語:Extensible Stylesheet Language Transformations,縮寫XSLT)是一種樣式轉(zhuǎn)換標(biāo)記語言,可以將XML數(shù)據(jù)檔轉(zhuǎn)換為另外的XML或其它格式,如HTML網(wǎng)頁,純文字。XSLT最末的T字母表示英語中的“轉(zhuǎn)換”(transformation)。
簡單來說,開發(fā)人員可以借助 XSLT 技術(shù)編寫一個(gè) XML 文件,并使用該文件將一種 XML 格式轉(zhuǎn)換為另一種 XML 。即:在對(duì)接復(fù)雜格式 XML 數(shù)據(jù)源時(shí),開發(fā)人員可以編寫一個(gè)后綴為 .xsl 的文件,并使用該文件將數(shù)據(jù)源格式轉(zhuǎn)換為自己需要的格式(比如可以適配 XML 反序列化的格式)。
從一個(gè)簡單的 XML 文件開始:
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
.
.
.
</catalog>
如果直接在瀏覽器打開這個(gè)文件:
假設(shè)我們只關(guān)心所有的 title 信息,可以使用下面的 cdcatalog.xsl 文件,該文件可以將 cdcatalog.xml 轉(zhuǎn)為 XmlSerializer 所需要的格式:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsl:for-each select="catalog/cd">
<string>
<xsl:value-of select="title"/>
</string>
</xsl:for-each>
</ArrayOfString>
</xsl:template>
</xsl:stylesheet>
為了可以在瀏覽器中直接觀察到轉(zhuǎn)換效果,可以選擇把 XSL 樣式表鏈接到 XML 文檔:向 XML 文檔(”cdcatalog.xml”)添加 XSL 樣式表引用即可。
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
.
.
.
</catalog>
刷新瀏覽器,打開開發(fā)者工具:
也可以在: https://www.coderbusy.com/demos/2021/1531/cdcatalog.xml 查看在線示例。
從上面的操作可以看出,調(diào)試 XLS 文件的成本是很低的,開發(fā)者可以很容易對(duì) XLS 文件進(jìn)行更改,并在短時(shí)間之內(nèi)得到運(yùn)行結(jié)果。
在 C# 中,可以使用 XslCompiledTransform 進(jìn)行 XSL 轉(zhuǎn)換。以下代碼展示這個(gè)轉(zhuǎn)換過程:
XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load("cdcatalog.xsl");
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
using (var xw = new XmlTextWriter(sw) { Formatting = Formatting.Indented })
{
xsl.Transform("cdcatalog.xml", xw);
}
}
var xml = sb.ToString();
Console.WriteLine(xml);
以上代碼會(huì)產(chǎn)生如下輸出:
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Empire Burlesque</string>
<string>Hide your heart</string>
<string>Greatest Hits</string>
<string>Still got the blues</string>
<string>Eros</string>
.
.
.
</ArrayOfString>
轉(zhuǎn)換 XML 不是目的,能直接拿到數(shù)據(jù)對(duì)象才是。以上的代碼完成了格式轉(zhuǎn)換,接著需要對(duì)轉(zhuǎn)換好的 XML 字符串反序列化:
var xmlSerializer = new XmlSerializer(typeof(List<string>));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
var list = (List<string>) xmlSerializer.Deserialize(ms);
foreach (var item in list)
{
Console.WriteLine(item);
}
}
以上代碼借助 XmlSerializer 實(shí)現(xiàn)了反序列化功能,這會(huì)產(chǎn)生以下輸出:
Empire Burlesque
Hide your heart
Greatest Hits
Still got the blues
Eros
...
本文所述的轉(zhuǎn)換和反序列化技術(shù)已經(jīng)在真實(shí)的生產(chǎn)環(huán)境中得到驗(yàn)證,千萬級(jí)的數(shù)據(jù)處理也毫不費(fèi)力。
本文包含的演示的代碼和數(shù)據(jù)可以在 Gitee 上找到:
https://gitee.com/coderbusy/demo/tree/master/hello-xslt/HelloXslt
一篇文章我們介紹了一個(gè)html/xml解析器——htmlparser,這篇文章我們介紹另外一個(gè)解析模塊htmlparser2,后者是對(duì)前者的重構(gòu),同時(shí)對(duì)前者的API做了部分兼容。
安裝
const { Parser } = require('htmlparser2');
const parser = new Parser(handler, options);
parser.parseComplete('html/xml內(nèi)容');
寫法
const { Parser } = require('htmlparser2');
const parser = new Parser(handler, options);
parser.parseComplete('html/xml內(nèi)容');
htmlparser2提供了一個(gè)解析器——Parser,初始化它至少需要一個(gè)handler,options是可選的。
handler是一個(gè)對(duì)象,在這個(gè)對(duì)象上可以設(shè)置很多的鉤子函數(shù),Parser解析時(shí)會(huì)在每個(gè)階段運(yùn)行對(duì)應(yīng)的鉤子函數(shù)。
以下是可以設(shè)置的所有的鉤子函數(shù),
htmlparser模塊是通過正則表達(dá)式來解析html內(nèi)容的,而htmlparser2則不同,它會(huì)按順序讀取html的每個(gè)字符,并且推測(cè)后面字符是標(biāo)簽名、屬性還是其他的類型,所以htmlparser2在解析完每一個(gè)標(biāo)簽后都會(huì)運(yùn)行相應(yīng)的鉤子函數(shù)。
先來看一下例子,
圖1
圖1中設(shè)置了所有的鉤子函數(shù)以便來說明每個(gè)鉤子函數(shù)的作用,運(yùn)行一下,
圖2
對(duì)照?qǐng)D1和圖2就能看出來每個(gè)鉤子函數(shù)的運(yùn)行時(shí)機(jī),這其中有以下幾個(gè)鉤子函數(shù)需要注意一下。
除了自定義handler以外,htmlparser2還提供了幾個(gè)handler,比如DomHandler,用法如下:
圖3
運(yùn)行一下,我們看看結(jié)果,
圖4
如果4所示,DomHandler處理的結(jié)果是以數(shù)組的形式輸出的,在每個(gè)單元數(shù)據(jù)中還可以拿到上一個(gè)、下一個(gè)以及父節(jié)點(diǎn)的數(shù)據(jù)。
htmlparser2還可以通過操作流Stream解析內(nèi)容,寫法如下:
圖5
這篇文章和上一篇是姊妹篇,都是介紹解析html/xml內(nèi)容的模塊,通過對(duì)比,我們發(fā)現(xiàn)htmlparser2模塊功能更強(qiáng)大一些,也更靈活一些,同時(shí)也兼容htmlparser模塊的一些接口。雖然兩者功能類似,但是這給了我們更多的選擇性。
喜歡我的文章就關(guān)注我吧,有問題可以發(fā)表評(píng)論,我們一起學(xué)習(xí),共同成長!
面是我們?nèi)绾卧?JavaScript 中輕松地將 JSON 轉(zhuǎn)換為 CSV:
function jsonToCsv(items) {
const header = Object.keys(items[0]); const headerString = header.join(','); // handle null or undefined values here
const replacer = (key, value) => value ?? ''; const rowItems = items.map((row) =>
header
.map((fieldName) => JSON.stringify(row[fieldName], replacer))
.join(',')
); // join header and body, and break into separate lines
const csv = [headerString, ...rowItems].join('\r\n'); return csv;
}const obj = [
{ color: 'red', maxSpeed: 120, age: 2 },
{ color: 'blue', maxSpeed: 100, age: 3 },
{ color: 'green', maxSpeed: 130, age: 2 },
];const csv = jsonToCsv(obj);console.log(csv);
這將是 CSV 輸出:
color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2
了解步驟
我們創(chuàng)建了一個(gè)可重用的 jsonToCsv() 函數(shù)來讓我們將多個(gè) JSON 字符串轉(zhuǎn)換為 CSV。 它需要一個(gè)包含對(duì)象的數(shù)組。 每個(gè)對(duì)象將在 CSV 輸出中占據(jù)一行。
我們?cè)诖撕瘮?shù)中所做的第一件事是獲取將用于 CSV 標(biāo)頭的所有鍵。 我們希望數(shù)組中的所有對(duì)象都具有相同的鍵,因此我們使用 Object.keys() 方法將鍵從第一個(gè)對(duì)象項(xiàng)中提取到數(shù)組中。
const obj = [
{ color: 'red', maxSpeed: 120, age: 2 },
{ color: 'blue', maxSpeed: 100, age: 3 },
{ color: 'green', maxSpeed: 130, age: 2 },
];// { color: 'red', maxSpeed: 120, age: 2 }
console.log(obj[0]);// [ 'color', 'maxSpeed', 'age' ]
console.log(Object.keys(obj[0]));
獲取鍵后,我們調(diào)用數(shù)組的 join() 方法將所有元素連接成 CSV 標(biāo)頭字符串。
const header = ['color', 'maxSpeed', 'age'];const headerString = arr.join(',');console.log(headerString); // color,maxSpeed,age
接下來,我們創(chuàng)建一個(gè)函數(shù),該函數(shù)將作為回調(diào)傳遞給 JSON.stringify() 函數(shù)的 replacer 參數(shù)。 此函數(shù)將處理 JSON 數(shù)組中對(duì)象的未定義或空屬性值。
const obj = { prop1: 'Earth', prop2: undefined };// replace undefined property values with empty string ('')
const replacer = (key, value) => value ?? '';const str = JSON.stringify(obj, replacer);// {"prop1":"Earth","prop2":""}
console.log(str);
然后我們使用 Array map() 方法從每個(gè)對(duì)象中獲取屬性值。 map() 接受一個(gè)回調(diào)函數(shù),該函數(shù)在每個(gè)數(shù)組元素上調(diào)用以返回一個(gè)轉(zhuǎn)換。
此回調(diào)使用標(biāo)頭數(shù)組來獲取每個(gè)對(duì)象的所有鍵。 再次調(diào)用 map(),它會(huì)遍歷每個(gè)鍵,獲取對(duì)象中該鍵的對(duì)應(yīng)值,并使用 JSON.stringify() 將其轉(zhuǎn)換為字符串。
這個(gè)對(duì) map() 的內(nèi)部調(diào)用最終會(huì)產(chǎn)生一個(gè)數(shù)組,該數(shù)組包含數(shù)組中當(dāng)前對(duì)象的所有字符串化屬性值。
const header = ['color', 'maxSpeed', 'age'];const row = { color: 'red', maxSpeed: 120, age: 2 };const replacer = (key, value) => value ?? '';const rowItem = header.map((fieldName) =>
JSON.stringify(row[fieldName], replacer)
);// array of stringified property values
console.log(rowItem); // [ '"red"', '120', '2' ]
將對(duì)象轉(zhuǎn)換為屬性值數(shù)組后,使用 join() 將數(shù)組轉(zhuǎn)換為 CSV 行。
['"red"', '120', '2'].join(',') // -> "red",120,2
因此,這種轉(zhuǎn)換發(fā)生在 JSON 數(shù)組中的每個(gè)對(duì)象上,以生成 CSV 行列表,存儲(chǔ)在我們?cè)际纠械?rowItems 變量中。
為了生成最終的 CSV 輸出,我們使用擴(kuò)展語法 (...) 將 headerString 和 rowItems 組合到一個(gè)數(shù)組中。
const headerString = ['color', 'maxSpeed', 'age'];const rowItems = ['"red",120,2', '"blue",100,3', '"green",130,2'];[headerString, ...rowItems];
/*
Output ->
[
[ 'color', 'maxSpeed', 'age' ],
'"red",120,2',
'"blue",100,3',
'"green",130,2'
]
*/
然后我們?cè)谶@個(gè)數(shù)組上調(diào)用 join() 并使用 '\r\n' 字符串作為分隔符,以創(chuàng)建一個(gè)帶有 CSV 標(biāo)題的字符串,并且每個(gè) CSV 行位于單獨(dú)的行中。
const headerString = ['color', 'maxSpeed', 'age'];const rowItems = ['"red",120,2', '"blue",100,3', '"green",130,2'];console.log([headerString, ...rowItems].join('\r\n'));
/*
color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2
*/
關(guān)注七爪網(wǎng),獲取更多APP/小程序/網(wǎng)站源碼資源!
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。