我正在使用XMLBuilder
包在Node.js
中创建XML文件。除了一件事,一切都很好。我试图向root
元素添加属性,但由于某种原因,它被添加到child
元素中。
我已经这样声明了我的root
元素:
//Create the header for XML
var builder = require('xmlbuilder');
var root = builder.create('test:XMLDocument')
root.att('schemaVersion', "2.0")
root.att('creationDate', '2020-10-09T09:53:00.000+02:00')
root.att('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance")
root = root.ele('MyBody')
root = root.ele('MyEvents')
在声明之后,当我试图向我的根元素添加更多属性时:
root.att('new1','additionalAttributes1')
root.att('new2','additionalAttributes2')
它被附加到MyEvents
上,看起来像这样:
<?xml version="1.0"?>
<test:XMLDocument schemaVersion="2.0" creationDate="2020-10-09T09:53:00.000+02:00">
<MyBody>
<MyEvents new1="additionalAttributes1" new2="additionalAttributes2">
</MyEvents>
</MyBody>
</test:XMLDocument>
但我希望生成的XML文件显示如下:
<?xml version="1.0"?>
<test:XMLDocument schemaVersion="2.0" creationDate="2020-10-09T09:53:00.000+02:00" new1="additionalAttributes1" new2="additionalAttributes2">
<MyBody>
<MyEvents>
</MyEvents>
</MyBody>
</test:XMLDocument>
我知道,如果我像这样声明我的XML元素,那么我能够实现预期的结果,但由于我将其传递给另一个函数,我无法像这样声明它:
//Create the header for XML
var builder = require('xmlbuilder');
var root = builder.create('test:XMLDocument')
root.att('schemaVersion', "2.0")
root.att('creationDate', '2020-10-09T09:53:00.000+02:00')
root.att('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance")
root.att('new1','additionalAttributes1')
root.att('new2','additionalAttributes2')
root = root.ele('MyBody')
root = root.ele('MyEvents')
我试着添加.up((,看看它是否被添加到父对象中,但没有成功。有人能帮我吗?当我有多个孩子时,我如何将属性添加到父母身上并达到所需的结果?
你只需要上升两次
var builder = require('xmlbuilder')
var root = builder.create('test:XMLDocument')
root.att('schemaVersion', '2.0')
root.att('creationDate', '2020-10-09T09:53:00.000+02:00')
root.att('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
root = root.ele('MyBody')
root = root.ele('MyEvents')
root = root.up().up()
root.att('new1','additionalAttributes1')
root.att('new2','additionalAttributes2')
console.log(root.end({pretty: true}));
输出
<?xml version="1.0"?>
<test:XMLDocument schemaVersion="2.0" creationDate="2020-10-09T09:53:00.000+02:00" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" new1="additionalAttributes1" new2="additionalAttributes2">
<MyBody>
<MyEvents/>
</MyBody>
</test:XMLDocument>