我正在尝试将以下值数组解析为一个XML文件,可以使用以下XSD文件对其进行验证。我希望使用Javascript完成此操作。
var myArray = [ '"elem11","elem12","elem13","elem14","elem15"',
'"elem21","elem22","elem23","elem24","elem25"',
'"elem31","elem32","elem33","elem34","elem35"' ]
XSD:
<xsd:element name="myArray">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="myArray" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="elemX1" type="xsd:string"/>
<xsd:element name="elemX2" type="xsd:string"/>
<xsd:element name="elemX3" type="xsd:string"/>
<xsd:element name="elemX4" type="xsd:integer" minOccurs="0"/>
<xsd:element name="elemX5" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
答案 0 :(得分:0)
基于您的XSD,结果XML的结构如下:
<myArray>
<myArray>
<elemX1></elemX1>
<elemX2></elemX2>
<elemX3></elemX3>
<elemX4></elemX4>
<elemX5></elemX5>
</myArray>
</myArray>
有几种方法可以完成此操作。以下是使用libxmljs的示例。
var libxml = require("libxmljs");
var myArray = [ '"elem11","elem12","elem13","elem14","elem15"',
'"elem21","elem22","elem23","elem24","elem25"',
'"elem31","elem32","elem33","elem34","elem35"' ]
var doc = new libxml.Document();
if (doc) {
var root = doc.node('myArray');
myArray.forEach(function(entry) {
var entries = entry.split(",");
var child = root.node("myArray")
child.node("elemX1", entries[0].replace(/"/g, ''));
child.node("elemX2", entries[1].replace(/"/g, ""));
child.node("elemX3", entries[2].replace(/"/g, ""));
child.node("elemX4", entries[3]);
child.node("elemX5", entries[4]);
});
console.log(doc.toString());
}
这将产生输出:
<?xml version="1.0" encoding="UTF-8"?>
<myArray>
<myArray>
<elemX1>elem11</elemX1>
<elemX2>elem12</elemX2>
<elemX3>elem13</elemX3>
<elemX4>elem14</elemX4>
<elemX5>elem15</elemX5>
</myArray>
<myArray>
<elemX1>elem21</elemX1>
<elemX2>elem22</elemX2>
<elemX3>elem23</elemX3>
<elemX4>elem24</elemX4>
<elemX5>elem25</elemX5>
</myArray>
<myArray>
<elemX1>elem31</elemX1>
<elemX2>elem32</elemX2>
<elemX3>elem33</elemX3>
<elemX4>elem34</elemX4>
<elemX5>elem35</elemX5>
</myArray>
</myArray>