我目前正在使用xml2js。我正在尝试解析具有以下结构的 xml 文件:
<?xml version='1.0' encoding='UTF-8'?>
<document>
<teachers>
<teacher>
<id>1</id>
<first_name>Gawen</first_name>
<last_name>Rosenstengel</last_name>
<email>grosenstengel0@google.com.hk</email>
</teacher>
<teacher>
<id>2</id>
<first_name>Fabien</first_name>
<last_name>Stanford</last_name>
<email>fstanford1@usa.gov</email>
</teacher>
</teachers>
<ships>
<ship>
<id>1</id>
<name>Brazelton</name>
<length>218</length>
<crew>555</crew>
</ship>
<ship>
<id>2</id>
<name>Ailsbury</name>
<length>121</length>
<crew>197</crew>
</ship>
</ships>
</document>
我使用以下异步方法(Typescript)来解析它:
async parseXMLFile(path: string): Promise<any | undefined> {
let xmlString = await fs.readFile(path, "latin1");
let result = await xml2js.parseStringPromise(xmlString, xmlParseOptions);
return result;
}
我使用的选项如下:
export const xmlParseOptions = {
explicitArray: false,
mergeAttrs: true,
explicitRoot: false
};
解析产生的输出:
{
teachers: {
teacher: [
{ id: '1', first_name: 'Gawen', last_name: 'Rosenstengel', email: 'grosenstengel0@google.com.hk' },
{ id: '2', first_name: 'Fabien', last_name: 'Stanford', email: 'fstanford1@usa.gov' }
]
},
ships: {
ship: [
{ id: '1', name: 'Brazelton', length: '218', crew: '555' },
{ id: '2', name: 'Ailsbury', length: '121', crew: '197' }
]
}
}
我现在的问题是通过哪些设置可以实现以下格式:
{
teachers: [
{ id: '1', first_name: 'Gawen', last_name: 'Rosenstengel', email: 'grosenstengel0@google.com.hk' },
{ id: '2', first_name: 'Fabien', last_name: 'Stanford', email: 'fstanford1@usa.gov' }
],
ships: [
{ id: '1', name: 'Brazelton', length: '218', crew: '555' },
{ id: '2', name: 'Ailsbury', length: '121', crew: '197' }
]
}
我对 xml 比较陌生,所以也许我做错了什么。我已经提前感谢您的回答:)