[英]modify XML file using XMLDOM
我无法使用XMLSerializer修改xml。我的代码是
var xml = request.responseText;
var DOMParser = require( 'xmldom' ).DOMParser;
var parser = new DOMParser();
var document = parser.parseFromString( xml, 'text/xml' );
document.getElementsByTagName( "a:Value" ).nodeValue = 12345;
var XMLSerializer = require( 'xmldom' ).XMLSerializer;
var serializer = new XMLSerializer();
var writetofile = serializer.serializeToString( document );
console.log( "writetofile" + writetofile );
我得到的XML具有相同的旧值,而不是12345。
请让我知道如何解决此问题。尝试所有选项。仍然不起作用。
尝试将第5行更改为
document.getElementsByTagName("a:Value")[0].childNodes[0].data = '124241';
编辑
这是我在“ runkit.com ”上编写的代码,以演示如何解决注释中提到的问题。
// some make-up xml
var xml = `
<root>
<a:table xmlns:a="http://www.w3schools.com/furniture">
<a:name>African Coffee Table</a:name>
<a:width>80</a:width>
<a:length>120</a:length>
<a:Value>old value</a:Value>
</a:table>
</root>`;
var DOMParser = require( 'xmldom' ).DOMParser;
var parser = new DOMParser();
var document = parser.parseFromString( xml, 'text/xml' );
// this won't work, but no error
document.getElementsByTagName( "a:Value" ).nodeValue = 12345;
// check: you will get "undefined" on the console
console.log( document.getElementsByTagName("a:Value").nodeValue);
// check: you will get "old value" on the console
console.log( document.getElementsByTagName("a:Value")[0].childNodes[0].data );
// here is another try
document.getElementsByTagName("a:Value")[0].childNodes[0].data = '12345';
// next, you will get "12345" on the console as expected
console.log( document.getElementsByTagName("a:Value")[0].childNodes[0].data );
var XMLSerializer = require( 'xmldom' ).XMLSerializer;
var serializer = new XMLSerializer();
var xmlstring = serializer.serializeToString( document );
console.log( "xmlstring: \n" + xmlstring );
console.log()的相关输出:
undefined
old value
12345
xmlstring:
<root>
<a:table xmlns:a="http://www.w3schools.com/furniture">
<a:name>African Coffee Table</a:name>
<a:width>80</a:width>
<a:length>120</a:length>
<a:Value>12345</a:Value>
</a:table>
</root>
感谢您再次答复。
我找到了解决方案,希望将其粘贴在此处,这将有助于其他使用过的textContent属性在行下方更改
document.getElementsByTagName( "a:Value" ).nodeValue = 12345;
至
document.getElementsByTagName( "a:Value" )[0].textcontent = 12345;
有效!!! 现在,我得到了具有更改值的整个XML。 干杯!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.