我在跳过空节点值时遇到问题。下面我通过从 XML 文件读取不同的标签来创建一个对象。问题是,当尝试读取“Addresse5”的 nodeValue 时,我收到一条错误,指出节点值未定义。
var getCustomerAddress1 = xmlDoc.getElementsByTagName('address1');
var getCustomerAddress2 = xmlDoc.getElementsByTagName('address2');
var getCustomerAddress3 = xmlDoc.getElementsByTagName('address3');
var getCustomerAddress4 = xmlDoc.getElementsByTagName('address4');
var getCustomerAddress5 = xmlDoc.getElementsByTagName('address5');
var getCustomerNumber = xmlDoc.getElementsByTagName('customerNumber');
var txt2 = {};
for (var i = 0; i < len; i++) {
txt2 = {
Addresse1: getCustomerAddress1[i].childNodes[0].nodeValue,
Addresse2: getCustomerAddress2[i].childNodes[0].nodeValue,
Addresse3: getCustomerAddress3[i].childNodes[0].nodeValue,
Addresse4: getCustomerAddress4[i].childNodes[0].nodeValue,
Addresse5: getCustomerAddress5[i].childNodes[0].nodeValue,
};
}
我想要的是跳过读取或用一些文本替换空的nodeValue,但我不知道如何实现这一点。
编辑:
这就是我的 xml 文件的样子
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<collection>
<DeliveryAddress>
<address1>sdasdsadsa</address1>
<address2>1asdasdas1</address2>
<address3>sdfsdf</address3>
<address4>Daasdasd</address4>
<address5></address5>
<customerNumber>5825252</customerNumber>
</DeliveryAddress>
</collection>
提前致谢
最佳答案
当您无法确定 XML 文档中是否存在允许的值时,您可以创建一个函数来过滤未定义的值并将其替换为空字符串或您喜欢的任何内容,然后将值传递给它。
var getCustomerAddress1 = xmlDoc.getElementsByTagName('address1');
var getCustomerAddress2 = xmlDoc.getElementsByTagName('address2');
var getCustomerAddress3 = xmlDoc.getElementsByTagName('address3');
var getCustomerAddress4 = xmlDoc.getElementsByTagName('address4');
var getCustomerAddress5 = xmlDoc.getElementsByTagName('address5');
var getCustomerNumber = xmlDoc.getElementsByTagName('customerNumber');
// function to add
function filterUndefined(xmlValue) {
if (xmlValue != null) { // check if type is null or undefined
return xmlValue;
}
else {
return ""; // return empty string or anything else you like
}
}
var txt2 = {};
for (var i = 0; i < len; i++) {
// when filling this object with values, filter undefined ones and replace them with ""
txt2 = {
Addresse1: filterUndefined(getCustomerAddress1[i].childNodes[0].nodeValue),
Addresse2: filterUndefined(getCustomerAddress2[i].childNodes[0].nodeValue),
Addresse3: filterUndefined(getCustomerAddress3[i].childNodes[0].nodeValue),
Addresse4: filterUndefined(getCustomerAddress4[i].childNodes[0].nodeValue),
Addresse5: filterUndefined(getCustomerAddress5[i].childNodes[0].nodeValue),
};
}
关于javascript - 忽略 XML 文件中的空 nodeValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408394/