如何访问对象中类型为<Item>的XML条目。

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

how to access xml entries of type <Item> in an object

问题

以下是翻译好的部分:

如下所示的代码中,我正在处理一个tiff文件。最内层Promise中的img对象包含以键值形式表示的一些数据。对象img.fileDirectory.GDAL_METADATA包含以下发布的数据。

现在我的问题是,由于我想要访问STATISTICS_MAXIMUMSTATISTICS_MEAN等内容,我如何访问在GDALMetadata中显示的内容?

GDALMetadata

<GDALMetadata>
  <Item name="STATISTICS_MAXIMUM" sample="0">21.122838228436</Item>
  <Item name="STATISTICS_MEAN" sample="0">1.2389914218174</Item>
  <Item name="STATISTICS_MINIMUM" sample="0">-4.6630500033646</Item>
  <Item name="STATISTICS_STDDEV" sample="0">2.0382729681586</Item>
</GDALMetadata>

代码

response.on('close', async () => {
  console.log('Retrieved all data');
  readFile("./test-1.tiff")
    .then((data) => {
      dataAsArrayBuffer = data.buffer
      fromArrayBuffer(dataAsArrayBuffer)
        .then((geoTIFF) => {
          geoTIFF.getImage()
            .then((img) => {
              console.log(img.fileDirectory.GDAL_METADATA);//<==============
              console.log(img.getWidth(), img.getHeight(), img.getSamplesPerPixel());
            })
            .catch((e) => console.log("img.errorMessage:", e))
        })
        .catch((e) => console.log("geoTIFF.errorMessage:", e))
    })
    .catch((e) => console.log("data.errorMessage:", e))
});
英文:

as shown in the below posted code, i am processing a tiff file. the img object in the inner-most promise contains some data in a form of key-value.
the object img.fileDirectory.GDAL_METADATA contains the data posted below.

now my question is, as i would like to have access to STATISTICS_MAXIMUM,STATISTICS_MEAN,...etc. how can i have access to contents shown in GDALMetadata

GDALMetadata

&lt;GDALMetadata&gt;
  &lt;Item name=&quot;STATISTICS_MAXIMUM&quot; sample=&quot;0&quot;&gt;21.122838228436&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_MEAN&quot; sample=&quot;0&quot;&gt;1.2389914218174&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_MINIMUM&quot; sample=&quot;0&quot;&gt;-4.6630500033646&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_STDDEV&quot; sample=&quot;0&quot;&gt;2.0382729681586&lt;/Item&gt;
&lt;/GDALMetadata&gt;

code:

response.on(&#39;close&#39;, async()=&gt;{
	console.log(&#39;Retrieved all data&#39;);
	readFile(&quot;./test-1.tiff&quot;)
	.then((data)=&gt;{
		dataAsArrayBuffer = data.buffer
		fromArrayBuffer(dataAsArrayBuffer)
		.then((geoTIFF)=&gt;{
			geoTIFF.getImage()
			.then((img)=&gt; {
				console.log(img.fileDirectory.GDAL_METADATA);//&lt;==============
				console.log(img.getWidth(), img.getHeight(), img.getSamplesPerPixel());
			})
			.catch((e)=&gt;console.log(&quot;img.errorMessage:&quot;,e))
		})
		.catch((e)=&gt; console.log(&quot;geoTIFF.errorMessage:&quot;,e))
	})
	.catch((e)=&gt; console.log(&quot;data.errorMessage:&quot;,e))
});

答案1

得分: 2

以下是翻译好的部分:

NodeJS domparsers

例如 jsdom

const jsdom = require("jsdom");
const meta = `<GDALMetadata>
  <Item name="STATISTICS_MAXIMUM" sample="0">21.122838228436</Item>
  <Item name="STATISTICS_MEAN" sample="0">1.2389914218174</Item>
  <Item name="STATISTICS_MINIMUM" sample="0">-4.6630500033646</Item>
  <Item name="STATISTICS_STDDEV" sample="0">2.0382729681586</Item>
</GDALMetadata>`;

const dom = new jsdom.JSDOM(meta);
const stats = [...dom.window.document.querySelectorAll("Item")]
 .map(item => ({[item.getAttribute('name')]:+item.textContent})); // 使用一元加号将字符串转换为数字
console.log(stats);

内置浏览器 DOMParser

const meta = `<GDALMetadata>
  <Item name="STATISTICS_MAXIMUM" sample="0">21.122838228436</Item>
  <Item name="STATISTICS_MEAN" sample="0">1.2389914218174</Item>
  <Item name="STATISTICS_MINIMUM" sample="0">-4.6630500033646</Item>
  <Item name="STATISTICS_STDDEV" sample="0">2.0382729681586</Item>
</GDALMetadata>`;

const parser = new DOMParser();
const doc1 = parser.parseFromString(meta, "application/xml");
const stats = [...doc1.querySelectorAll("Item")]
 .map(item => ({[item.getAttribute('name')]:+item.textContent})); // 使用一元加号将字符串转换为数字
console.log(stats)
英文:

NodeJS domparsers

For example jsdom

const jsdom = require(&quot;jsdom&quot;);
const meta = `&lt;GDALMetadata&gt;
  &lt;Item name=&quot;STATISTICS_MAXIMUM&quot; sample=&quot;0&quot;&gt;21.122838228436&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_MEAN&quot; sample=&quot;0&quot;&gt;1.2389914218174&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_MINIMUM&quot; sample=&quot;0&quot;&gt;-4.6630500033646&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_STDDEV&quot; sample=&quot;0&quot;&gt;2.0382729681586&lt;/Item&gt;
&lt;/GDALMetadata&gt;`;

const dom = new jsdom.JSDOM(meta);
const stats = [...dom.window.document.querySelectorAll(&quot;Item&quot;)]
 .map(item =&gt; ({[item.getAttribute(&#39;name&#39;)]:+item.textContent})); // convert the string to number using unary plus
console.log(stats);

Built-in Browser DOMParser

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const meta = `&lt;GDALMetadata&gt;
  &lt;Item name=&quot;STATISTICS_MAXIMUM&quot; sample=&quot;0&quot;&gt;21.122838228436&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_MEAN&quot; sample=&quot;0&quot;&gt;1.2389914218174&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_MINIMUM&quot; sample=&quot;0&quot;&gt;-4.6630500033646&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_STDDEV&quot; sample=&quot;0&quot;&gt;2.0382729681586&lt;/Item&gt;
&lt;/GDALMetadata&gt;`;

const parser = new DOMParser();
const doc1 = parser.parseFromString(meta, &quot;application/xml&quot;);
const stats = [...doc1.querySelectorAll(&quot;Item&quot;)]
 .map(item =&gt; ({[item.getAttribute(&#39;name&#39;)]:+item.textContent})); // convert the string to number using unary plus
console.log(stats)

<!-- end snippet -->

答案2

得分: 0

在Node.js服务器端使用cheerio等解析器解析HTML/XML是可行的。

尝试以下代码,它会加载你的字符串,查找所有的Item元素,循环它们并获取文本值。然后,你可以根据需要构建结果对象:

const cheerio = require('cheerio');

const inputData = `<GDALMetadata>
  <Item name="STATISTICS_MAXIMUM" sample="0">21.122838228436</Item>
  <Item name="STATISTICS_MEAN" sample="0">1.2389914218174</Item>
  <Item name="STATISTICS_MINIMUM" sample="0">-4.6630500033646</Item>
  <Item name="STATISTICS_STDDEV" sample="0">2.0382729681586</Item>
</GDALMetadata>`;

const $ = cheerio.load(inputData, {
  xmlMode: true
});

const result = {};

// 选择所有的 Item 元素,获取每个元素的文本值
$('Item').each(function(i, elm) {
  console.log($(this).text());
  // 构建对象 attributeName:value
  result[$(this).attr('name')] = $(this).text();
});

console.log(result);

请注意,这段代码使用cheerio库加载XML数据,并遍历所有的Item元素,将它们的属性名作为对象的键,文本值作为对象的值。最后,将结果打印出来。

英文:

Parsing HTML/XML on server side with Node.js. can be done with parsers such as cheerio

Try this, it loads your string, finds all Item elements, loops them and gets text value. You can then construct results object according to your needs:

const cheerio = require(&#39;cheerio&#39;);

const inputData = `&lt;GDALMetadata&gt;
  &lt;Item name=&quot;STATISTICS_MAXIMUM&quot; sample=&quot;0&quot;&gt;21.122838228436&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_MEAN&quot; sample=&quot;0&quot;&gt;1.2389914218174&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_MINIMUM&quot; sample=&quot;0&quot;&gt;-4.6630500033646&lt;/Item&gt;
  &lt;Item name=&quot;STATISTICS_STDDEV&quot; sample=&quot;0&quot;&gt;2.0382729681586&lt;/Item&gt;
&lt;/GDALMetadata&gt;`;

const $ = cheerio.load(inputData, {
      xmlMode: true
    });

const result = {};

// select all Item elements, get text value for each
$(&#39;Item&#39;).each(function(i, elm) {
    console.log($(this).text());
// construct object attributeName:value
    result[$(this).attr(&#39;name&#39;)] = $(this).text();    
});

console.log(result);

huangapple
  • 本文由 发表于 2023年6月27日 17:55:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563683.html
匿名

发表评论

匿名网友

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

确定