0

我正在Node.js使用XMLBuilder包创建 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() 以查看它是否被添加到父级但没有运气。当我有多个孩子并达到所需的结果时,有人可以帮助我如何将属性添加到父母吗?

4

1 回答 1

2

你只需要上两次

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>
于 2020-10-06T09:15:43.790 回答