我有一个可行的例子。当前,我通过子节点值在节点树中的假定位置来查找子节点值,但是由于有时缺少节点,因此该方法无法完美运行。通过元素名称而不是XML树位置查找子节点的最简单方法是什么?
var n = document.getElementById("myInputId");
n.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function testResults() {
const { value } = myInputId;
const foundState = [...xmlDoc.querySelectorAll('STATE')]
.find(possibleMatch => possibleMatch.textContent === value);
const unit = foundState.parentElement;
console.log(unit.innerHTML);
document.getElementById("stateNode").innerHTML = unit.children[0].textContent;
document.getElementById("gdpNode").innerHTML = unit.children[1].textContent;
document.getElementById("populationNode").innerHTML = unit.children[2].textContent;
/*how can I find a node based on its name rather than position in the XML tree?*/
document.getElementById("codeNode").innerHTML = unit.children[3].textContent;
}
var parser, xmlDoc, x, i;
var text =
"<STATE_DATA>" +
"<UNIT>" +
"<STATE>Wisconsin</STATE>" +
"<GDP>232,300,000,000</GDP>" +
"<POPULATION>5,800,000</POPULATION>" +
"<CODE>WI</CODE>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Alabama</STATE>" +
"<GDP>165,800,000,000</GDP>" +
"<POPULATION>4,900,000</POPULATION>" +
"<CODE>AL</CODE>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>California</STATE>" +
/*California is missing the GDP node*/
"<POPULATION>39,600,000</POPULATION>" +
"<CODE>CA</CODE>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Texas</STATE>" +
"<GDP>1,600,000,000,000</GDP>" +
"<POPULATION>28,300,000</POPULATION>" +
"<CODE>TX</CODE>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Michigan</STATE>" +
"<GDP>382,000,000</GDP>" +
"<POPULATION>10,000,000</POPULATION>" +
"<CODE>MI</CODE>" +
"</UNIT>" +
"</STATE_DATA>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
<input list="myInput" id="myInputId" value="">
<button id="myButton" onClick="testResults()">submit</button>
<datalist id="myInput">
<option id="AL">Alabama</option>
<option id="CA">California</option>
<option id="MI">Michigan</option>
<option id="TX">Texas</option>
<option id="WI">Wisconsin</option>
</datalist>
<p>State node: <span id="stateNode"></span></p>
<p>GDP node: <span id="gdpNode"></span></p>
<p>Population node: <span id="populationNode"></span></p>
<p>Code node: <span id="codeNode"></span></p>
答案 0 :(得分:2)
您已经发现,使用节点位置通常不是可靠的方法。根据XML结构的大小,我建议使用Unit节点中的sub-querySelector
:
您已经拥有UNIT节点(const unit = foundState.parentElement;
),因此只需进行如下设置:
var ustate = unit.querySelector('STATE') ? unit.querySelector('STATE').textContent: "Not Found";
var ugdp = unit.querySelector('GDP') ? unit.querySelector('GDP').textContent: "Not Found";
...
然后更新您的HTML:
document.getElementById("stateNode").innerHTML = ustate ;
document.getElementById("gdpNode").innerHTML = ugdp ;