简体   繁体   中英

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. For example the following query syntax works to get the root node obj and attribute value:

result.Home.$.Name;

However, on request I will not if root will be Home, Foo, etc. I tried the following, but did not work:

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? Not sure if that is xml2js, typescript, of js specific. I am use to using xpath to query so this is a lot different.

Thanks in advance!

The top level object returned by xml2js only has one own property, and that corresponds to the name of root element. We can leverage this knowledge to access the property corresponding to the root XML element without knowing element name statically.

First we will get the own property keys of the result object. The easiest way to do that is using 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

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

Now we will use this rootKey to access the object representing the root element, regardless of its tag name.

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].$;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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