Untitled
unknown
plain_text
a year ago
1.7 kB
10
Indexable
class SimpleXMLParser {
parse(xml: string): any {
// Remove XML declaration
xml = xml.replace(/<\?xml.*?\?>/, '').trim();
return this.parseNode(xml);
}
private parseNode(xml: string): any {
const obj: any = {};
let tagName = this.getTagName(xml);
let content = this.getTagContent(xml, tagName);
console.log(tagName, content)
// Process inner tags recursively
while (content.includes('<')) {
const innerTag = this.getTagName(content);
const innerContent = this.getTagContent(content, innerTag);
if (!obj[innerTag]) {
obj[innerTag] = [];
}
obj[innerTag].push(this.parseNode(`<${innerTag}>${innerContent}</${innerTag}>`));
content = content.replace(`<${innerTag}>${innerContent}</${innerTag}>`, '').trim();
}
if (!content.includes('<')) {
obj['_text'] = content;
}
return obj;
}
private getTagName(xml: string): string {
const match = xml.match(/^<([\w-]+)>/);
return match ? match[1] : '';
}
private getTagContent(xml: string, tagName: string): string {
const regex = new RegExp(`<${tagName}>(.*?)</${tagName}>`, 's');
const match = xml.match(regex);
return match ? match[1].trim() : '';
}
}
// Example usage
const xmlString = `
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
`;
const parser = new SimpleXMLParser();
const result = parser.parse(xmlString);
//console.log(result);Editor is loading...
Leave a Comment