XMLBuilder 将属性添加到 XML 文件中的错误节点

XMLBuilder adds the attributes to wrong node in the XML file

我正在使用 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() 以查看它是否被添加到 parent 但没有成功。有人可以帮我当我有多个 child 时如何将属性添加到 parent 并达到所需的结果?

你只要上去两次就可以了

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>