AgentSkillsCN

symfony-7-4-css-selector

Symfony 7.4 CssSelector组件参考文档,用于将CSS选择器转换为XPath表达式。在进行CSS转XPath、使用CSS选择器查询HTML/XML、集成DOMXPath、SimpleXMLElement,或与DomCrawler协同工作时,均可参考该文档。触发器包括:CssSelector、CssSelectorConverter、CSS转XPath、toXPath、HTML/XML查询、使用CSS选择器查询DOM。

SKILL.md
--- frontmatter
name: "symfony-7-4-css-selector"
description: "Symfony 7.4 CssSelector component reference for converting CSS selectors to XPath expressions. Use when working with CSS to XPath conversion, HTML/XML querying with CSS selectors, DOMXPath, SimpleXMLElement, or DomCrawler integration. Triggers on: CssSelector, CssSelectorConverter, CSS to XPath, toXPath, HTML/XML querying, DOM querying with CSS selectors."

Symfony 7.4 CssSelector Component

GitHub: https://github.com/symfony/css-selector Docs: https://symfony.com/doc/7.4/components/css_selector.html

Quick Reference

Installation

bash
composer require symfony/css-selector

Basic Usage - Convert CSS to XPath

php
use Symfony\Component\CssSelector\CssSelectorConverter;

$converter = new CssSelectorConverter();

// Simple element selector
$xpath = $converter->toXPath('div.item > h4 > a');
// Result: descendant-or-self::div[@class and contains(concat(' ',normalize-space(@class), ' '), ' item ')]/h4/a

Using with DOMXPath

php
$document = new \DOMDocument();
$document->loadHTML($htmlContent);
$xpath = new \DOMXPath($document);

$converter = new CssSelectorConverter();
$expression = $converter->toXPath('div.content > p.intro');
$nodes = $xpath->query($expression);

foreach ($nodes as $node) {
    echo $node->textContent;
}

Using with SimpleXMLElement

php
$xml = simplexml_load_string($xmlContent);
$converter = new CssSelectorConverter();
$expression = $converter->toXPath('book > author');
$results = $xml->xpath($expression);

HTML Mode vs XML Mode

php
// HTML mode (default) - case-insensitive tag/attribute matching
$converter = new CssSelectorConverter();

// XML mode - case-sensitive matching
$converter = new CssSelectorConverter(false);

Supported CSS Selectors

SelectorExampleSupported
Elementdiv, p, aYes
Class.classYes
ID#idYes
Attribute[attr], [attr=value]Yes
Descendantdiv pYes
Childdiv > pYes
Adjacent siblingdiv + pYes
General siblingdiv ~ pYes
:first-childli:first-childYes
:last-childli:last-childYes
:nth-child()li:nth-child(2n+1)Yes
:enabled / :disabledinput:enabledYes
:checkedinput:checkedYes
:is() / :where():is(h1, h2)Yes (7.1+)
:first-of-typeli:first-of-typeElement only (not *)
Pseudo-elements::beforeNo
:hover / :focusa:hoverNo
:link / :visiteda:linkNo

Full Documentation

For complete details including all supported selectors, limitations, and integration patterns, see references/css-selector.md.