1

我正在尝试在 nodejs 脚本中使用 xml-stream 解析非常大的 XML 文件。

xml-stream 可以在这里找到 - https://github.com/assistunion/xml-stream

   <?xml version="1.0"?>
<Products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:lang="en-us" version="0.96" versionTimestamp="2012-02-07T03:00:00Z" fooKey="6402420af51e08">
    <Product>
        <id>296834</id>
        <name>Thing</name>
        <Photos>
            <Photo>
                <MediaURL>http://url.com/to/image/file</MediaURL>
            </Photo>
            <Photo>
                <MediaURL>http://url.com/to/image/secondfile</MediaURL>
            </Photo>
            <Photo>
                <MediaURL>http://url.com/to/image/thirdfile</MediaURL>
            </Photo>
        </Photos>
    </Product>
</Products>

我的nodejs代码看起来像这样......

var fs        = require('fs')
, path      = require('path')
, XmlStream = require('xml-stream')
;

// Create a file stream and pass it to XmlStream
var stream = fs.createReadStream(path.join(__dirname, 'samplekirby.xml'));
var xml = new XmlStream(stream);

xml.preserve('Product', true);
xml.collect('Photos');
xml.on('endElement: Product', function(item) {
   console.log(item);
});

输出...

{ '$children': 
[ { '$children': [Object], '$text': '296834', '$name': 'id' },
 { '$children': [Object], '$text': 'Thing', '$name': 'name' },
 { '$children': [Object], Photo: [Object], '$name': 'Photos' } ],
id: { '$children': [ '296834' ], '$text': '296834', '$name': 'id' },
name: { '$children': [ 'Thing' ], '$text': 'Thing', '$name': 'name' },
Photos: 
{ '$children': [ [Object], [Object], [Object] ],
 Photo: { '$children': [Object], MediaURL: [Object], '$name': 'Photo' },
 '$name': 'Photos' },
'$name': 'Product' }

如何获取图像 URL?

我已经以各种顺序在各个节点上尝试了 .collect() 和 .preserve() 。这个库似乎没有很多更复杂的使用示例。我有非常大的 XML 文件,而 xml2js 无法处理它。如果我能弄清楚如何以某种方式增加深度,我会对这个 lib 选择感到满意。

4

1 回答 1

1

如果您只想获取 URL

var fs = require('fs'),
    path = require('path'),
    XmlStream = require('xml-stream');

// Create a file stream and pass it to XmlStream
var stream = fs.createReadStream(path.join(__dirname, 'sample.xml'));
var xml = new XmlStream(stream);

xml.collect('Photo');
xml.on('endElement: Product', function(product) {
    console.log(JSON.stringify(product, null, 2));
})

输出:

{
  "id": "296834",
  "name": "Thing",
  "Photos": {
    "Photo": [
      {
        "MediaURL": "http://url.com/to/image/file"
      },
      {
        "MediaURL": "http://url.com/to/image/secondfile"
      },
      {
        "MediaURL": "http://url.com/to/image/thirdfile"
      }
    ]
  }
}
于 2017-01-12T03:11:35.520 回答