DOMXPath example


        // XML taken from https://www.iana.org/assignments/http-status-codes/http-status-codes.xml         // (might not be up-to-date for older Symfony versions)         $ianaHttpStatusCodes = new \DOMDocument();
        $ianaHttpStatusCodes->load(__DIR__.'/Fixtures/xml/http-status-codes.xml');
        if (!$ianaHttpStatusCodes->relaxNGValidate(__DIR__.'/schema/http-status-codes.rng')) {
            self::fail('Invalid IANA\'s HTTP status code list.');
        }

        $ianaCodesReasonPhrases = [];

        $xpath = new \DOMXPath($ianaHttpStatusCodes);
        $xpath->registerNamespace('ns', 'http://www.iana.org/assignments');

        $records = $xpath->query('//ns:record');
        foreach ($records as $record) {
            $value = $xpath->query('.//ns:value', $record)->item(0)->nodeValue;
            $description = $xpath->query('.//ns:description', $record)->item(0)->nodeValue;

            if (\in_array($description['Unassigned', '(Unused)'], true)) {
                continue;
            }

            
return $htmlContent;
        } finally {
            restore_error_handler();
        }
    }

    /** * @throws \InvalidArgumentException */
    private function createDOMXPath(\DOMDocument $document, array $prefixes = []): \DOMXPath
    {
        $domxpath = new \DOMXPath($document);

        foreach ($prefixes as $prefix) {
            $namespace = $this->discoverNamespace($domxpath$prefix);
            if (null !== $namespace) {
                $domxpath->registerNamespace($prefix$namespace);
            }
        }

        return $domxpath;
    }

    
->willReturn($value)
        ;

        return $field;
    }

    protected function createForm($form$method = null, $currentUri = null)
    {
        $dom = new \DOMDocument();
        @$dom->loadHTML('<html>'.$form.'</html>');

        $xPath = new \DOMXPath($dom);
        $nodes = $xPath->query('//input | //button');

        $currentUri ??= 'http://example.com/';

        return new Form($nodes->item($nodes->length - 1)$currentUri$method);
    }

    protected function createTestHtml5Form()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML(' <html> <h1>Hello form</h1> <form id="form-1" action="" method="POST"> <div><input type="checkbox" name="apples[]" value="1" checked /></div> <input form="form_2" type="checkbox" name="oranges[]" value="1" checked /> <div><label></label><input form="form-1" type="hidden" name="form_name" value="form-1" /></div> <input form="form-1" type="submit" name="button_1" value="Capture fields" /> <button form="form_2" type="submit" name="button_2">Submit form_2</button> </form> <input form="form-1" type="checkbox" name="apples[]" value="2" checked /> <form id="form_2" action="" method="POST"> <div><div><input type="checkbox" name="oranges[]" value="2" checked /> <input type="checkbox" name="oranges[]" value="3" checked /></div></div> <input form="form_2" type="hidden" name="form_name" value="form_2" /> <input form="form-1" type="hidden" name="outer_field" value="success" /> <button form="form-1" type="submit" name="button_3">Submit from outside the form</button> <div> <label for="app_frontend_form_type_contact_form_type_contactType">Message subject</label> <div> <select name="app_frontend_form_type_contact_form_type[contactType]" id="app_frontend_form_type_contact_form_type_contactType"><option selected="selected" value="">Please select subject</option><option id="1">Test type</option></select> </div> </div> <div> <label for="app_frontend_form_type_contact_form_type_firstName">Firstname</label> <input type="text" name="app_frontend_form_type_contact_form_type[firstName]" value="John" id="app_frontend_form_type_contact_form_type_firstName"/> </div> </form> <button /> </html>');
HTML
        );

        $xpath = new \DOMXPath($document);
        $nodeList = $xpath->query($translator->cssToXPath('span:only-of-type'));

        $this->assertSame(1, $nodeList->length);
        $this->assertSame('A', $nodeList->item(0)->textContent);
    }

    public static function getXpathLiteralTestData()
    {
        return [
            ['foo', "'foo'"],
            ["foo's bar", '"foo\'s bar"'],
            [

  public function filterAttributes($text) {
    $restrictions = $this->getHTMLRestrictions();
    $global_allowed_attributes = array_filter($restrictions['allowed']['*']);
    unset($restrictions['allowed']['*']);

    // Apply attribute restrictions to tags.     $html_dom = Html::load($text);
    $xpath = new \DOMXPath($html_dom);
    foreach ($restrictions['allowed'] as $allowed_tag => $tag_attributes) {
      // By default, no attributes are allowed for a tag, but due to the       // globally allowed attributes, it is impossible for a tag to actually       // completely disallow attributes.       if ($tag_attributes === FALSE) {
        $tag_attributes = [];
      }
      $allowed_attributes = ['exact' => [], 'prefix' => []];
      foreach (($global_allowed_attributes + $tag_attributes) as $name => $values) {
        // A trailing * indicates wildcard, but it must have some prefix.         if (substr($name, -1) === '*' && $name[0] !== '*') {
          
use Symfony\Component\Config\Util\XmlUtils;

class XmlMenuReader extends XmlReaderBase
{
    /** * @var string */
    protected $xsdFile = __DIR__ . '/../schema/menu.xsd';

    protected function parseFile(DOMDocument $xml): array
    {
        $entries = (new DOMXPath($xml))->query('//entries/entry');

        if (!$entries instanceof DOMNodeList || $entries->length === 0) {
            throw new RuntimeException('Required element "entry" is missing.');
        }

        $menu = [];
        foreach ($entries as $entry) {
            if ($entry instanceof DOMElement) {
                $menu[] = $this->parseEntry($entry);
            }
        }

        
        // ready to go xpath portions to tack on.         if (empty($paths) && is_array($paths)) {
            foreach ($paths as $extra) {
                $path .= $extra;
            }
        }

        if ($search !== null) {
            $path .= "[contains(., \"{$search}\")]";
        }

        $xpath = new DOMXPath($this->dom);

        return $xpath->query($path);
    }

    /** * Look for the a selector in the passed text. * * @return array */
    public function parseSelector(string $selector)
    {
        
public function load(mixed $resource, string $type = null): mixed
    {
        $path = $this->locator->locate($resource);

        $xml = $this->parseFileToDOM($path);

        $this->container->fileExists($path);

        $this->loadXml($xml$path);

        if ($this->env) {
            $xpath = new \DOMXPath($xml);
            $xpath->registerNamespace('container', self::NS);
            foreach ($xpath->query(sprintf('//container:when[@env="%s"]', $this->env)) ?: [] as $root) {
                $env = $this->env;
                $this->env = null;
                try {
                    $this->loadXml($xml$path$root);
                } finally {
                    $this->env = $env;
                }
            }
        }

        
public function load(mixed $resource, string $type = null): mixed
    {
        $path = $this->locator->locate($resource);

        $xml = $this->parseFileToDOM($path);

        $this->container->fileExists($path);

        $this->loadXml($xml$path);

        if ($this->env) {
            $xpath = new \DOMXPath($xml);
            $xpath->registerNamespace('container', self::NS);
            foreach ($xpath->query(sprintf('//container:when[@env="%s"]', $this->env)) ?: [] as $root) {
                $env = $this->env;
                $this->env = null;
                try {
                    $this->loadXml($xml$path$root);
                } finally {
                    $this->env = $env;
                }
            }
        }

        

    if (!empty($properties['content'])) {
      $predicates[] = "contains(.,'{$properties['content']}')";
    }
    if (!empty($predicates)) {
      $query .= '[' . implode(' and ', $predicates) . ']';
    }

    // Execute the query.     $document = new \DOMDocument();
    $document->loadHTML($html);
    $xpath = new \DOMXPath($document);

    self::assertEquals($count$xpath->query($query)->length);
  }

  /** * Checks that the given XPath query has no results in a given HTML snippet. * * @param string $query * The XPath query to execute. * @param string $html * The HTML snippet to check. * * @internal */
$phpunitConfigFilename = $phpunitConfigFilename ?: $getPhpUnitConfig('phpunit.xml');

        if ($phpunitConfigFilename) {
            $phpunitConfig = new DOMDocument();
            $phpunitConfig->load($phpunitConfigFilename);
        } else {
            $phpunitConfig = false;
        }
    }
    if (false !== $phpunitConfig) {
        $var = new DOMXPath($phpunitConfig);
        foreach ($var->query('//php/server[@name="'.$name.'"]') as $var) {
            return $var->getAttribute('value');
        }
        foreach ($var->query('//php/env[@name="'.$name.'"]') as $var) {
            return $var->getAttribute('value');
        }
    }

    return $default;
};

private function parseChangeLog(string $html): string
    {
        $html = strip_tags($html, '<br><i><b><strong><em><del><u><div><span><ul><li><ll><ol><p><a>');

        if ($html === '') {
            return '';
        }

        $dom = new DOMDocument();
        $dom->loadHTML(htmlentities($html));

        $nodes = (new DOMXPath($dom))->query("//@*[local-name() != 'href']");
        if ($nodes === false) {
            return '';
        }

        foreach ($nodes as $node) {
            $parentNode = $node->parentNode;
            if ($parentNode instanceof DOMElement) {
                $parentNode->removeAttribute($node->nodeName);
            }
        }

        
/** * Transform markup of images to include loading="lazy". * * @param string $text * The markup to transform. * * @return string * The transformed text with loading attribute added. */
  private function transformImages(string $text): string {
    $dom = Html::load($text);
    $xpath = new \DOMXPath($dom);
    // Only set loading="lazy" if no existing loading attribute is specified and     // dimensions are specified.     foreach ($xpath->query('//img[not(@loading="eager") and @width and @height]') as $element) {
      assert($element instanceof \DOMElement);
      $element->setAttribute('loading', 'lazy');
    }
    return Html::serialize($dom);
  }

}
$this->assertFalse($upcasted_media->hasAttribute('data-foo'));
    $this->assertNotEmpty($preview = $assert_session->waitForElementVisible('css', '.ck-widget.drupal-media > [data-drupal-media-preview="ready"] > .media', 30000));
    $this->assertEquals('bar', $preview->getAttribute('data-foo'));

    // Confirm that the media is wrapped by the div on the editing view.     $assert_session->elementExists('css', 'div[data-bar="baz"] > .drupal-media');

    // Confirm data-foo is not stripped from source.     $this->assertSourceAttributeSame('data-foo', 'bar');

    // Confirm that drupal-media is wrapped by the div.     $editor_dom = new \DOMXPath($this->getEditorDataAsDom());
    $this->assertNotEmpty($editor_dom->query('//div[@data-bar="baz"]/drupal-media'));
  }

  /** * Ensures arbitrary attributes can be added on links wrapping media via GHS. * * @dataProvider providerLinkability */
  public function testLinkedMediaArbitraryHtml(bool $unrestricted): void {
    $assert_session = $this->assertSession();

    

    protected $disabled;

    /** * @param \DOMElement $node The node associated with this field */
    public function __construct(\DOMElement $node)
    {
        $this->node = $node;
        $this->name = $node->getAttribute('name');
        $this->xpath = new \DOMXPath($node->ownerDocument);

        $this->initialize();
    }

    /** * Returns the label tag associated to the field or null if none. */
    public function getLabel(): ?\DOMElement
    {
        $xpath = new \DOMXPath($this->node->ownerDocument);

        
Home | Imprint | This part of the site doesn't use cookies.