gpt4 book ai didi

javascript - 当数据库值为空时,如何在 xml 标签之间插入空格

转载 作者:行者123 更新时间:2023-11-30 01:02:35 26 4
gpt4 key购买 nike

这是由 php 代码动态生成的 xml 文件的一部分。

标签的内部值从数据库表中获取并动态插入到 xml 文件中。

当数据库中的字段/列值为 null 或为空时,生成的 xml 标记类似于以下情况 标签如下。

 <Code>141113-0001</Code>
<EntryDate>14-11-2013</EntryDate>
<LabTestNo/>

我在控制台上收到以下错误

   Uncaught TypeError: Cannot read property 'nodeValue' of undefined 

我的 JavaScript 代码是这样的:

 xmlDoc=xmlht.responseXML;
tableData=xmlDoc.getElementsByTagName('data');
document.getElementById('Code').value=tableData[0].getElementsByTagName('Code')[0].childNodes[0].nodeValue;

如果数据库表中的列为空,如何使用 javascript 在文本字段中插入空白,以及如果表中的列为空或为空,如何返回 xml 标记之间的空白。让标签看起来像

    <LabTestNo> "here comes the white space if column is null/empty" </LabTestNo>

最佳答案

此处无需更改 XML。短/空标签是有效的 XML 并且可以解析。您可以在 XML 上使用查询选择器和 Xpath 表达式。

错误 Uncaught TypeError: Cannot read property 'nodeValue' of undefined 是因为您尝试读取元素的子节点而不验证它是否存在(使用 .childNodes[ 0].nodeValue)。您可以使用 ?. 对象运算符来避免这种情况。

此外,更好的属性是textContent。它返回全文内容(包括后代节点)。

结合起来你会得到类似的东西:

const value = aDocument.querySelector(aSelector)?.textContent || 'default';

更具体一点:

const xmlString = `<data><Code>141113-0001</Code>
<EntryDate>14-11-2013</EntryDate>
<LabTestNo/>
</data>`;

const xmlResponse = (new DOMParser()).parseFromString(xmlString, 'text/xml');

const data = Array.from(xmlResponse.querySelectorAll('data')).map(
(item) => ({
Code: item.querySelector('Code')?.textContent || '',
EntryDate: item.querySelector('EntryDate')?.textContent || '',
LabTestNo: item.querySelector('LabTestNo')?.textContent || ''
})
);

console.log(data);

关于javascript - 当数据库值为空时,如何在 xml 标签之间插入空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19973065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com