解析在 javascript 中作为响应接收到的 XML,
Posted
技术标签:
【中文标题】解析在 javascript 中作为响应接收到的 XML,【英文标题】:Parsing XML that was received as an response in javascript, 【发布时间】:2021-10-11 22:15:27 【问题描述】:function parsingXML(APIResponse)
var txt = APIResponse.responseXML;
if (window.DOMParser)
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
else // Internet Explorer
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
console.log(APIResponse)
console.log(xmlDoc.getElementsByTagName("SCID_WEB_REF_NUMBER")[0].childNodes[0].nodeValue);
这是控制台中显示的错误
error TypeError: Cannot read property 'childNodes' of undefined
responseXML 是:
"<NewDataSet>\r\n <Table>\r\n <SCID_WEB_REF_NUMBER>PIVP1005202112332381</SCID_WEB_REF_NUMBER>\r\n <SCID_SBIL_SUPERVISOR_ID>O2026</SCID_SBIL_SUPERVISOR_ID>\r\n <SCID_TYPE_OF_CLAIM>Sampoorna Suraksha</SCID_TYPE_OF_CLAIM>\r\n <SCID_INVESTIGATION_TYPE>Document Procurement</SCID_INVESTIGATION_TYPE>\r\n <SCID_POLICY_NUMBER>72112051821</SCID_POLICY_NUMBER>\r\n <SCID_CUSTOMERID_EMPLOYEEID>50846</SCID_CUSTOMERID_EMPLOYEEID>\r\n <SCID_CLAIMID>5082036</SCID_CLAIMID>\r\n <SCID_UNIQUE_ID>72112051821|50846|5082036|</SCID_UNIQUE_ID>\r\n <SCID_NAME_OF_LA>samay</SCID_NAME_OF_LA>\r\n <SCID_DOB_OF_LA>1985-07-05T00:00:00+05:30</SCID_DOB_OF_LA>\r\n <SCID_STATE_OF_LA>Delhi</SCID_STATE_OF_LA>\r\n <SCID_INCOME_OF_LA>0</SCID_INCOME_OF_LA>\r\n <SCID_PINCODE>0</SCID_PINCODE>\r\n <SCID_DATE_OF_COMMENCEMENT>2019-12-08T00:00:00+05:30</SCID_DATE_OF_COMMENCEMENT>\r\n <SCID_SUM_ASSURED>500000</SCID_SUM_ASSURED>\r\n <DATE_OF_REVIVAL>0001-01-01T00:00:00+05:30</DATE_OF_REVIVAL>\r\n <SCID_DATE_OF_DEATH>0001-01-01T00:00:00+05:30</SCID_DATE_OF_DEATH>\r\n <SCID_NAME_OF_CLAIMANT>rahul</SCID_NAME_OF_CLAIMANT>\r\n <SCID_CONTACT_NO_OF_CLAIMANT>9895123482</SCID_CONTACT_NO_OF_CLAIMANT>\r\n <SCID_CONTACT_NUMBER_OF_LA>8975412327</SCID_CONTACT_NUMBER_OF_LA>\r\n <SCID_STATUS>Inprogress</SCID_STATUS>\r\n <SCID_CREATEDATE>2021-05-10T12:33:23+05:30</SCID_CREATEDATE>\r\n <SCVID_VENDOR_SUPERVISOR_ID>VS4</SCVID_VENDOR_SUPERVISOR_ID>\r\n <SCVID_VENDOR_INV_ID>VI1</SCVID_VENDOR_INV_ID>\r\n <SCVID_EXPIRES_ON>2023-06-06T00:00:00+05:30</SCVID_EXPIRES_ON>\r\n <SCVID_ASSIGNED_BY>VS4</SCVID_ASSIGNED_BY>\r\n <SCVID_STATUS>AllocatedToInvestigator</SCVID_STATUS>\r\n <ALLOCATION_DATE>2021-06-19T16:25:11+05:30</ALLOCATION_DATE>\r\n <AGE>36</AGE>\r\n <POLICYDURATION>-15</POLICYDURATION>\r\n </Table>\r\n</NewDataSet>"
这是存储在 APIResponse 变量中并传递给 parsingXML 函数的内容
我如何解析这个 xml 并从这些 xml 标签中获取数据,无论我尝试了什么,我都无法弄清楚。
目标是从 xml 响应中提取所有数据并将其存储在变量中以供进一步处理。
【问题讨论】:
【参考方案1】:您收到此错误消息是因为您的目标节点没有任何子节点。试试这个
target = xmlDoc.getElementsByTagName("SCID_WEB_REF_NUMBER")
console.log(target[0].textContent)
输出应该是:
"PIVP1005202112332381"
【讨论】:
以上是关于解析在 javascript 中作为响应接收到的 XML,的主要内容,如果未能解决你的问题,请参考以下文章
如何将从 json 接收到的 ko.observable 字符串解析为整数(数字)值