代码行是
readXML(): void {
// testing the function
let xmlstr = `<book><title>Some title</title>
<description>some description </description>
<author>
<id>1</id>
<name>some author name</name>
</author>
<review>nice book</review>
<review>this book sucks</review>
<review>amazing work</review></book>
`;
// converting to DOM Tree
const parser = new DOMParser();
const srcDOM = parser.parseFromString(xmlstr, "application/xml");
// Converting DOM Tree To JSON.
console.log(this.xml2json(srcDOM));
}
xml2json(srcDOM): any {
const children = Array.from(srcDOM.children);
// base case for recursion.
if (!children.length) {
return srcDOM.innerHTML
}
// initializing object to be returned.
let jsonResult = {};
for (let child of children) {
// checking is child has siblings of same name.
let childIsArray = children.filter(eachChild => eachChild.nodeName === child.nodeName).length > 1;
// if child is array, save the values as array, else as strings.
if (childIsArray) {
if (jsonResult[child.nodeName] === undefined) {
jsonResult[child.nodeName] = [this.xml2json(child)];
} else {
jsonResult[child.nodeName].push(this.xml2json(child));
}
} else {
jsonResult[child.nodeName] = this.xml2json(child);
}
}
return jsonResult;
};
此项目有问题eachchild.nodeName
,并引发以下错误
Property 'nodeName' does not exist on type '{}'.
代码按预期运行...我如何告诉Typescript该对象是什么并且它确实具有该属性?
谢谢!
上下文:我正在遍历XML字符串。