如何选择xlink:href属性不含'specyfic'的元素
Got it, let's walk through how to count those SVG <image> elements where the xlink:href attribute doesn't contain the string 'specyfic' — whether there are zero, one, or multiple matches. Here are a few practical approaches depending on your use case:
1. Browser-side JavaScript (for frontend scenarios)
If you're working with an SVG embedded in a web page, use the DOM API to filter and count the elements:
// Grab all <image> elements in the SVG const allImageElements = document.querySelectorAll('image'); // Filter to keep only those without 'specyfic' in their xlink:href const matchingElements = Array.from(allImageElements).filter(img => { const hrefValue = img.getAttribute('xlink:href'); // Include elements that don't have the xlink:href attribute at all return !hrefValue || !hrefValue.includes('specyfic'); }); // Get the final count const totalCount = matchingElements.length; console.log(`Number of non-specific elements: ${totalCount}`);
This handles edge cases like images that don't have an xlink:href attribute at all (they'll be counted as valid, since they don't contain the target string).
2. XPath (for XML/SVG document processing)
XPath is great if you're using tools that support it (like browser dev tools, Python's lxml library, or XML editors). Use this expression to directly get the count:
count(//image[not(contains(@xlink:href, 'specyfic'))])
For example, in your browser's console, you can run:
const count = document.evaluate( "count(//image[not(contains(@xlink:href, 'specyfic'))])", document, null, XPathResult.NUMBER_TYPE, null ).numberValue; console.log(count);
The XPath automatically includes elements without the xlink:href attribute, since contains(null, 'specyfic') returns false, and not(false) evaluates to true.
3. Command-line tool (xmllint, for batch file processing)
If you need to process local SVG files from the command line, use xmllint (common on Linux/macOS, or available via tools like Git Bash on Windows):
xmllint --xpath "count(//image[not(contains(@xlink:href, 'specyfic'))])" your-svg-file.svg
Running this will print the exact count of matching elements directly to your terminal.
Important note: Double-check the spelling — you wrote 'specyfic' (not the more common 'specific') so make sure all your expressions use that exact string to avoid mismatches.
内容的提问来源于stack exchange,提问作者Jerzy Gruszka

