2012-03-08 34 views

Trả lời

9

node-xml2js thư viện sẽ giúp bạn.

var xml2js = require('xml2js'); 

var parser = new xml2js.Parser(); 
var xml = '\ 
<yyy:response xmlns:xxx="http://domain.com">\ 
    <yyy:success>\ 
     <yyy:data>some-value</yyy:data>\ 
    </yyy:success>\ 
</yyy:response>'; 
parser.parseString(xml, function (err, result) { 
    console.dir(result['yyy:success']['yyy:data']); 
}); 
0

Trước tiên, bạn sẽ cần một thư viện để phân tích cú pháp XML. Nút lõi không cung cấp phân tích cú pháp XML.

Bạn sẽ tìm thấy một danh sách của họ ở đây: https://github.com/joyent/node/wiki/modules#wiki-parsers-xml

tôi sẽ khuyên bạn sử dụng libxmljs

-1

Có rất nhiều phương pháp để trích xuất thông tin từ tệp xml, Tôi đã sử dụng phương pháp chọn xpath để tìm nạp giá trị thẻ. https://cloudtechnzly.blogspot.in/2017/07/how-to-extract-information-from-xml.html

+0

Liên kết một giải pháp không phải là câu trả lời hay. Hãy tóm tắt bản chất của giải pháp ở đây hoặc đưa ra một mẫu mã. – TehSphinX

+0

kiểm tra liên kết này, sau đó bạn có thể nhận được một số ý tưởng https://cloudtechnzly.blogspot.in/2017/08/xml-to-json-conversion.html –

0

Bạn không cần phải phân tích nó để khai thác dữ liệu, chỉ cần sử dụng regexp:

str = "<yyy:response xmlns:xxx='http://example.com'> <yyy:success><yyy:data>some-value</yyy:data> </yyy:success></yyy:response>"; 
    var re = new RegExp("<yyy:data>(.*?)</yyy:data?>", "gmi"); 

    while(res = re.exec(str)){ console.log(res[1])} 

// some-value 
2

Bạn có thể làm điều đó dễ dàng hơn với camaro

const camaro = require('camaro') 

const xml = `<yyy:response xmlns:xxx='http://example.com'> <yyy:success><yyy:data>some-value</yyy:data> </yyy:success></yyy:response>` 

const template = { 
    data: '//yyy:data' 
} 

console.log(camaro(xml, template) 

Output:

{ data: 'some-value' } 
Các vấn đề liên quan