Node + xmldom:如何更改 javascript 中单个 XML 字段的值? [英] Node + xmldom: How do I change the value of a single XML field in javascript?
问题描述
使用 node v.0.10.29,Express v4.12.0 和 xmldom v0.1.19,我正在尝试执行以下操作:
Using node v.0.10.29, Express v4.12.0, and xmldom v0.1.19, I'm trying to do the following:
- 将 XML 文件读入字符串
- 使用将字符串转换为XML对象xmldom
- 将
字段设置为default test - 将 XML 对象转换回字符串
- Read an XML file into a string
- Convert the string into an XML object using xmldom
- Set the
<name>default</name>
field to<name>test</name>
- Convert the XML object back into a string
问题
问题是,在我设置
字段后,它在对象中正确设置,但是当我将其转换为字符串时,
字段恢复为旧值(错误).
Problem
The problem is that after I set the <name>
field, it sets correctly in the object, but when I convert it to a string, the <name>
field is back to being the old value (wrong).
代码如下:
var fs = require('fs');
var DOMParser = require('xmldom').DOMParser;
var XMLSerializer = require('xmldom').XMLSerializer;
var filename = "myFile.xml";
fs.readFile(filename, "utf-8", function (err,data)
{
//CREATE/PARSE XML OBJECT FROM STRING
var customerConfig = new DOMParser().parseFromString(data);
//SET VALUE TO "TEST" (<name>default</name> TO <name>test</name>)
customerConfig.getElementsByTagName("name")[0].childNodes[0].nodeValue = "test";
//THIS OUTPUTS "test" WHICH IS CORRECT -
console.log(customerConfig.getElementsByTagName("name")[0].childNodes[0].nodeValue);
//SERIALIZE TO STRING
var xmlString = new XMLSerializer().serializeToString(customerConfig);
//THIS OUTPUTS THE FULL XML FILE,
//BUT STILL SHOWS <name>default</name> AND NOT <name>test</name>
console.log(xmlString);
});
问题是
字段没有在字符串中设置为 test
......我在想序列化部分有问题?有人看到我做错了什么吗?
The problem is that the <name>
field isn't setting to test
in the string... I'm thinking there is a problem with the serialization part? Anyone see what I'm doing wrong?
谢谢!!
推荐答案
好吧,我找到了问题所在!
Well I figured out the problem!
我正在设置 nodeValue
但我确实需要设置 data
.所以我改了
I was setting nodeValue
but I really needed to set data
. So I changed
customerConfig.getElementsByTagName("name")[0].childNodes[0].nodeValue = "test";
到
customerConfig.getElementsByTagName("name")[0].childNodes[0].data= "test";
然后就成功了!
这篇关于Node + xmldom:如何更改 javascript 中单个 XML 字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!