我有一个xml,我想读取它的<block>
节点。但是当我在XPath下执行时,这给了我一个错误。
我要解析的xml:
let x = `<xml>
<block type="block_onGreenFlagClicked" id=";]jZ*Zs|[L-Sr{nhCB%V" x="25" y="0">
<field name="NAME1">When</field>
<statement name="function_name">
<block type="helper_Player__walkSecondsDrop" id="9lo_/{gKTxB6/FRH2Pw">
<field name="LABEL">Player.</field>
<field name="DROP_Player__walkSecondsDrop$">walkForwardForNSeconds</field>
</block>
</statement>
</block>
</xml>`;
let doms = new DOMParser()
let v = doms.parseFromString(x, 'text/xml')
let r = v.evaluate('/block',v, null, XPathResult.ANY_TYPE, null)
以下是结果:
XPathResult {invalidIteratorState: false, resultType: 4, iterateNext: function, snapshotItem: function, ANY_TYPE: 0…}
booleanValue: [Exception: TypeError: Failed to read the 'booleanValue' property from 'XPathResult': The result type is not a boolean.]
invalidIteratorState: false
numberValue: [Exception: TypeError: Failed to read the 'numberValue' property from 'XPathResult': The result type is not a number.]
resultType: 4
singleNodeValue: [Exception: TypeError: Failed to read the 'singleNodeValue' property from 'XPathResult': The result type is not a single node.]
snapshotLength: [Exception: TypeError: Failed to read the 'snapshotLength' property from 'XPathResult': The result type is not a snapshot.]
stringValue: [Exception: TypeError: Failed to read the 'stringValue' property from 'XPathResult': The result type is not a string.]
__proto__: XPathResult
我不知道我在做什么错?有人可以指导我吗?
答案 0 :(得分:4)
代码没有错。 /block
XPath表达式仅选择任何内容,因为根元素是xml
元素。将表达式更改为//block
会选择这两个block
元素。示例:
let x = `<xml>
<block type="block_onGreenFlagClicked" id=";]jZ*Zs|[L-Sr{nhCB%V" x="25" y="0">
<field name="NAME1">When</field>
<statement name="function_name">
<block type="helper_Player__walkSecondsDrop" id="9lo_/{gKTxB6/FRH2Pw">
<field name="LABEL">Player.</field>
<field name="DROP_Player__walkSecondsDrop$">walkForwardForNSeconds</field>
</block>
</statement>
</block>
</xml>`
let doms = new DOMParser()
let v = doms.parseFromString(x, 'text/xml')
let r = v.evaluate('//block', v, null, XPathResult.ANY_TYPE, null)
var s = new XMLSerializer();
var t = document.getElementById("output");
while ((n = r.iterateNext())) {
t.value += (s.serializeToString(n)) + "\n";
}
<body>
<textarea id="output" rows="15" cols="60"></textarea>
</body>