我有这个 XML 文件(精简):
<?xml version="1.0" encoding="UTF-8"?>
<Labels Version="24100002">
<Attendant>Attendant</Attendant>
<Attendant Index="1">Car Park Attendant</Attendant>
<Attendant Index="2">Entrance Attendant</Attendant>
<Attendant Index="3">Auditorium Attendant</Attendant>
<Attendant Index="4">Attendant 4</Attendant>
</Labels>
而且,我有这个 JavaScript 用于加载文件:
function loadXMLDoc(filename) {
return fetch(filename)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
}
在我的 HTML 文件中,我正在这样做(精简):
// Code snipped
// Fetch the XML and XSL files asynchronously
var [xsl, xml, labelsInfo] = await Promise.all([
loadXMLDoc('DutyHistory-transform.xsl'),
loadXMLDoc('DutyAssignHistory.xml'),
loadXMLDoc('LabelsInfo.XML')
]);
// Code snipped
// We have to add 1 to the indexing because the LabelsInfo file has a "Attendant" label too!
xsltProcessor.setParameter(null, 'index13', labelsInfo.documentElement.getElementsByTagName('Attendant')[1].textContent.trim());
xsltProcessor.setParameter(null, 'index14', labelsInfo.documentElement.getElementsByTagName('Attendant')[2].textContent.trim());
xsltProcessor.setParameter(null, 'index15', labelsInfo.documentElement.getElementsByTagName('Attendant')[3].textContent.trim());
有什么方法可以直接获取具有
Attendant
属性的所需 @Index
值吗?如你所见,此刻我增加了 1。效果很好。只是想知道我是否可以避免这种情况?
我的环境是WebView2。
查询选择器有效
const str = `<?xml version="1.0" encoding="UTF-8"?>
<Labels Version="24100002">
<Attendant>Attendant</Attendant>
<Attendant Index="1">Car Park Attendant</Attendant>
<Attendant Index="2">Entrance Attendant</Attendant>
<Attendant Index="3">Auditorium Attendant</Attendant>
<Attendant Index="4">Attendant 4</Attendant>
</Labels>`
const doc = new window.DOMParser().parseFromString(str, "text/xml");
const val = doc.querySelector('Attendant[Index]').textContent;
console.log(val)