简体   繁体   English

如果名称未知,xml2js 获取根节点 obj(可变)

[英]xml2js getting root node obj if name unknown (varies)

I am using xml2js to parse xml in my Aguilar CLI 9 project and wondering how to get the root node obj if the name is unknown (varies) on request.我在我的 Aguilar CLI 9 项目中使用 xml2js 来解析 xml 并且想知道如果名称未知(根据请求变化)如何获取根节点 obj。 For example the following query syntax works to get the root node obj and attribute value:例如,以下查询语法可用于获取根节点 obj 和属性值:

result.Home.$.Name;

However, on request I will not if root will be Home, Foo, etc. I tried the following, but did not work:但是,根据要求,如果 root 是 Home、Foo 等,我不会这样做。我尝试了以下方法,但没有奏效:

result[0].$.Name;

result.root.$.Name;

Also, I am very new to Angular and Typescript can anyone point me to some good documentation on what query syntax is being used?另外,我对 Angular 和 Typescript 非常陌生,谁能指出一些关于正在使用什么查询语法的好文档? Not sure if that is xml2js, typescript, of js specific.不确定这是否是 js 特定的 xml2js、typescript。 I am use to using xpath to query so this is a lot different.我习惯使用 xpath 进行查询,所以这有很大不同。

Thanks in advance!提前致谢!

The top level object returned by xml2js only has one own property, and that corresponds to the name of root element. xml2js返回的顶层object只有一个自己的属性,对应根元素的名称。 We can leverage this knowledge to access the property corresponding to the root XML element without knowing element name statically.我们可以利用这些知识来访问与根 XML 元素对应的属性,而无需静态知道元素名称。

First we will get the own property keys of the result object.首先,我们将获得结果 object 的自己的属性键。 The easiest way to do that is using Object.keys :最简单的方法是使用Object.keys

const result = await xml2js.parseStringPromise(someXML);

const keys = Object.keys(result);

Now, this results in an array of property keys, but since the object has only one, we can just use the first key现在,这会产生一个属性键数组,但由于 object 只有一个,我们可以只使用第一个键

const [rootKey] = Object.keys(result);

Now we will use this rootKey to access the object representing the root element, regardless of its tag name.现在我们将使用这个 rootKey 来访问代表根元素的 object,不管它的标签名称是什么。

result[rootKey];

Putting it together:把它放在一起:

import xml2js from 'xml2js';

async function processXML() {
  const result = await xml2js.parseStringPromise(someXML);

  const [rootKey] = Object.keys(result);

  const attributes = result[rootKey].$;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM