如何在NodeJS中从XML中提取数据?

huangapple go评论82阅读模式
英文:

How to extract data from xml in NodeJS?

问题

如何使用类似于NodeJS中的fast-xml-parser解析器提取numberMatched的值?

英文:

I have the following xml:

<?xml version="1.0" encoding="utf-8"?>
    <wfs:FeatureCollection xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.opengis.net/wfs/2.0 http://www.wfs.nrw.de/aaa-suite/schema/ogc/wfs/2.0/wfs.xsd" timeStamp="2023-06-01T13:31:53.444+02:00" numberReturned="0" numberMatched="9359426"/>

How can I extract the value of numberMatched using an xml parser like fast-xml-parser in NodeJS?

答案1

得分: 0

你需要将 ignoreAttributes 选项设置为 false

import { XMLParser } from "fast-xml-parser";

const XMLdata = `<?xml version="1.0" encoding="utf-8"?>
<wfs:FeatureCollection xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs/2.0 http://www.wfs.nrw.de/aaa-suite/schema/ogc/wfs/2.0/wfs.xsd" timeStamp="2023-06-01T13:31:53.444+02:00" numberReturned="0" numberMatched="9359426"/>`;

const parser = new XMLParser({
  ignoreAttributes: false,
  attributeNamePrefix: ""
});
let jObj = parser.parse(XMLdata);

console.log(jObj["wfs:FeatureCollection"].numberMatched);

如何在NodeJS中从XML中提取数据?

英文:

You need to set ignoreAttributes option to false

import { XMLParser } from &quot;fast-xml-parser&quot;;

const XMLdata = `&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;wfs:FeatureCollection xmlns:wfs=&quot;http://www.opengis.net/wfs/2.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot; http://www.opengis.net/wfs/2.0 http://www.wfs.nrw.de/aaa-suite/schema/ogc/wfs/2.0/wfs.xsd&quot; timeStamp=&quot;2023-06-01T13:31:53.444+02:00&quot; numberReturned=&quot;0&quot; numberMatched=&quot;9359426&quot;/&gt;`;

const parser = new XMLParser({
  ignoreAttributes: false,
  attributeNamePrefix: &quot;&quot;
});
let jObj = parser.parse(XMLdata);

console.log(jObj[&quot;wfs:FeatureCollection&quot;].numberMatched);

如何在NodeJS中从XML中提取数据?

huangapple
  • 本文由 发表于 2023年6月1日 19:38:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76381469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定