我正在嘗試使用 XPath 在 SVG 檔案中獲取一個元素。我嘗試了以下代碼,但singleNodeValue為空。在doc似乎是正確的,所以我想無論是evaluate()引數還是XPath是錯誤的,但我找不到任何錯誤。為什么不起作用?
JavaScript
fetch('test.svg')
.then(response => response.text())
.then(data=>{
const parser = new DOMParser();
const doc = parser.parseFromString(data, "text/xml");
console.log(doc);
const res = doc.evaluate("//symbol[@label='square']", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
console.log(res.singleNodeValue);
})
SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<symbol label ="square">
<rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
</symbol>
</svg>
經過一些測驗,我發現如果我洗掉xmlns="http://www.w3.org/2000/svg". 我在網上搜索并找到了一個答案:Why XPath does not work with xmlns attribute
uj5u.com熱心網友回復:
var data = '<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><symbol label ="square"><rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" /></symbol></svg>';
const parser = new DOMParser();
const doc = parser.parseFromString(data, "text/xml");
const res = doc.querySelector("symbol[label=square]");
console.log(res);
uj5u.com熱心網友回復:
您可以在 XPath 1 中使用命名空間決議器,并evaluate在 XPath 2 及更高版本(例如 Saxon-JS 2 支持)中使用函式,甚至使用 XPath 默認命名空間:
const svgString = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"
xmlns:dog = "http://dog.com/dog">
<symbol dog:label="square">
<rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
</symbol>
<symbol dog:label="cat">
<rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
</symbol>
</svg>`;
const doc = new DOMParser().parseFromString(svgString, 'application/xml');
const result = doc.evaluate(`//svg:symbol[@dog:label='cat']`, doc, function(prefix) { if (prefix === 'svg') return 'http://www.w3.org/2000/svg'; else if (prefix === 'dog') return 'http://dog.com/dog'; else return null; }, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
console.log(result.singleNodeValue);
const result2 = SaxonJS.XPath.evaluate(`//symbol[@dog:label = 'cat']`, doc, { xpathDefaultNamespace : 'http://www.w3.org/2000/svg', namespaceContext : { 'dog' : 'http://dog.com/dog' } });
console.log(result2);
<script src="https://www.saxonica.com/saxon-js/documentation/SaxonJS/SaxonJS2.rt.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/384948.html
標籤:javascript xml 路径
