View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html.parser.neko;
16  
17  import static org.htmlunit.BrowserVersionFeatures.JS_SCRIPT_IN_TEMPLATE_EXECUTED_ON_ATTACH;
18  
19  import java.io.IOException;
20  import java.io.StringReader;
21  import java.net.URL;
22  import java.nio.charset.Charset;
23  import java.util.ArrayDeque;
24  import java.util.Deque;
25  
26  import org.htmlunit.BrowserVersion;
27  import org.htmlunit.ObjectInstantiationException;
28  import org.htmlunit.WebClient;
29  import org.htmlunit.WebResponse;
30  import org.htmlunit.cyberneko.HTMLConfiguration;
31  import org.htmlunit.cyberneko.HTMLElements;
32  import org.htmlunit.cyberneko.HTMLScanner;
33  import org.htmlunit.cyberneko.HTMLTagBalancingListener;
34  import org.htmlunit.cyberneko.xerces.parsers.AbstractSAXParser;
35  import org.htmlunit.cyberneko.xerces.xni.Augmentations;
36  import org.htmlunit.cyberneko.xerces.xni.QName;
37  import org.htmlunit.cyberneko.xerces.xni.XMLAttributes;
38  import org.htmlunit.cyberneko.xerces.xni.XMLString;
39  import org.htmlunit.cyberneko.xerces.xni.XNIException;
40  import org.htmlunit.cyberneko.xerces.xni.parser.XMLInputSource;
41  import org.htmlunit.cyberneko.xerces.xni.parser.XMLParserConfiguration;
42  import org.htmlunit.html.DomCDataSection;
43  import org.htmlunit.html.DomComment;
44  import org.htmlunit.html.DomDocumentType;
45  import org.htmlunit.html.DomElement;
46  import org.htmlunit.html.DomNode;
47  import org.htmlunit.html.DomText;
48  import org.htmlunit.html.ElementFactory;
49  import org.htmlunit.html.Html;
50  import org.htmlunit.html.HtmlBody;
51  import org.htmlunit.html.HtmlElement;
52  import org.htmlunit.html.HtmlForm;
53  import org.htmlunit.html.HtmlHiddenInput;
54  import org.htmlunit.html.HtmlImage;
55  import org.htmlunit.html.HtmlPage;
56  import org.htmlunit.html.HtmlSvg;
57  import org.htmlunit.html.HtmlTable;
58  import org.htmlunit.html.HtmlTableRow;
59  import org.htmlunit.html.HtmlTemplate;
60  import org.htmlunit.html.ScriptElement;
61  import org.htmlunit.html.SubmittableElement;
62  import org.htmlunit.html.UnknownElementFactory;
63  import org.htmlunit.html.XHtmlPage;
64  import org.htmlunit.html.parser.HTMLParser;
65  import org.htmlunit.html.parser.HTMLParserDOMBuilder;
66  import org.htmlunit.html.parser.HTMLParserListener;
67  import org.htmlunit.javascript.host.html.HTMLBodyElement;
68  import org.htmlunit.svg.SvgElementFactory;
69  import org.htmlunit.util.StringUtils;
70  import org.w3c.dom.Node;
71  import org.xml.sax.Attributes;
72  import org.xml.sax.ContentHandler;
73  import org.xml.sax.Locator;
74  import org.xml.sax.SAXException;
75  import org.xml.sax.ext.LexicalHandler;
76  
77  /**
78   * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
79   *
80   * The parser and DOM builder. This class subclasses Xerces's AbstractSAXParser and implements
81   * the ContentHandler interface. Thus all parser APIs are kept private. The ContentHandler methods
82   * consume SAX events to build the page DOM
83   *
84   * @author Christian Sell
85   * @author David K. Taylor
86   * @author Chris Erskine
87   * @author Ahmed Ashour
88   * @author Marc Guillemot
89   * @author Ethan Glasser-Camp
90   * @author Sudhan Moghe
91   * @author Ronald Brill
92   * @author Frank Danek
93   * @author Carsten Steul
94   * @author Ronny Shapiro
95   * @author Atsushi Nakagawa
96   */
97  final class HtmlUnitNekoDOMBuilder extends AbstractSAXParser
98          implements ContentHandler, LexicalHandler, HTMLTagBalancingListener, HTMLParserDOMBuilder {
99  
100     // cache Neko Elements for performance and memory efficiency
101     private static final HTMLElements HTMLELEMENTS = new HTMLElements();
102 
103     private enum HeadParsed { YES, SYNTHESIZED, NO }
104 
105     private final HTMLParser htmlParser_;
106     private final HtmlPage page_;
107 
108     private Locator locator_;
109     private final Deque<DomNode> stack_ = new ArrayDeque<>();
110 
111     /** Did the snippet tried to overwrite the start node. */
112     private boolean snippetStartNodeOverwritten_;
113     private final int initialSize_;
114     private DomNode currentNode_;
115     private final boolean createdByJavascript_;
116     private final XMLString characters_ = new XMLString();
117     private HtmlUnitNekoDOMBuilder.HeadParsed headParsed_ = HeadParsed.NO;
118     private HtmlElement body_;
119     private boolean lastTagWasSynthesized_;
120     private HtmlForm consumingForm_;
121     private boolean formEndingIsAdjusting_;
122     private boolean insideSvg_;
123     private boolean insideTemplate_;
124 
125     private static final String FEATURE_AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
126     private static final String FEATURE_PARSE_NOSCRIPT
127         = "http://cyberneko.org/html/features/parse-noscript-content";
128 
129     /**
130      * Parses and then inserts the specified HTML content into the HTML content currently being parsed.
131      * @param html the HTML content to push
132      */
133     @Override
134     public void pushInputString(final String html) {
135         page_.registerParsingStart();
136         page_.registerInlineSnippetParsingStart();
137         try {
138             final WebResponse webResponse = page_.getWebResponse();
139             final Charset charset = webResponse.getContentCharset();
140             final String url = webResponse.getWebRequest().getUrl().toString();
141             final XMLInputSource in = new XMLInputSource(null, url, null, new StringReader(html), charset.name());
142             ((HTMLConfiguration) parserConfiguration_).evaluateInputSource(in);
143         }
144         finally {
145             page_.registerParsingEnd();
146             page_.registerInlineSnippetParsingEnd();
147         }
148     }
149 
150     /**
151      * Creates a new builder for parsing the specified response contents.
152      * @param node the location at which to insert the new content
153      * @param url the page's URL
154      * @param createdByJavascript if true the (script) tag was created by javascript
155      */
156     HtmlUnitNekoDOMBuilder(final HTMLParser htmlParser, final WebClient webClient,
157             final DomNode node, final URL url, final String htmlContent, final boolean createdByJavascript) {
158         super(createConfiguration(webClient.getBrowserVersion()));
159 
160         htmlParser_ = htmlParser;
161         page_ = (HtmlPage) node.getPage();
162 
163         currentNode_ = node;
164         for (final Node ancestor : currentNode_.getAncestors()) {
165             stack_.push((DomNode) ancestor);
166         }
167         createdByJavascript_ = createdByJavascript;
168 
169         final HTMLParserListener listener = webClient.getHTMLParserListener();
170         final boolean reportErrors = listener != null;
171         if (reportErrors) {
172             parserConfiguration_.setErrorHandler(new HtmlUnitNekoHTMLErrorHandler(listener, url, htmlContent));
173         }
174 
175         try {
176             setFeature(FEATURE_AUGMENTATIONS, true);
177             setFeature("http://cyberneko.org/html/features/report-errors", reportErrors);
178             setFeature(FEATURE_PARSE_NOSCRIPT, !webClient.isJavaScriptEnabled());
179             setFeature(HTMLScanner.ALLOW_SELFCLOSING_IFRAME, false);
180 
181             setContentHandler(this);
182             setLexicalHandler(this); //comments and CDATA
183         }
184         catch (final SAXException e) {
185             throw new ObjectInstantiationException("unable to create HTML parser", e);
186         }
187         initialSize_ = stack_.size();
188     }
189 
190     /**
191      * Sets the svg state; used for parsing fragments where the context
192      * (e.g. svg.innerHTML) is svg content.
193      *
194      * @param insideSvg true if the parsed content is svg content
195      */
196     void setInsideSvg(final boolean insideSvg) {
197         insideSvg_ = insideSvg;
198     }
199 
200     /**
201      * Create the configuration depending on the simulated browser.
202      * @return the configuration
203      */
204     private static XMLParserConfiguration createConfiguration(final BrowserVersion browserVersion) {
205         // HTMLElements.HTMLElementsWithCache are not thread safe
206         // because the cache is not synchronized
207         // we have to create a new one for each parser run
208         return new HTMLConfiguration(new HTMLElements.HTMLElementsWithCache(HTMLELEMENTS));
209     }
210 
211     /**
212      * {@inheritDoc}
213      */
214     @Override
215     public void setDocumentLocator(final Locator locator) {
216         locator_ = locator;
217     }
218 
219     /**
220      * {@inheritDoc}
221      */
222     @Override
223     public void startDocument() throws SAXException {
224         // nothing to do
225     }
226 
227     /** {@inheritDoc} */
228     @Override
229     public void startElement(final QName element, final XMLAttributes attributes, final Augmentations augs)
230         throws XNIException {
231         // augs might change so we store only the interesting part
232         lastTagWasSynthesized_ = augs.isSynthesized();
233         super.startElement(element, attributes, augs);
234     }
235 
236     /**
237      * {@inheritDoc}
238      */
239     @Override
240     public void startElement(final String namespaceURI, final String localName, final String qName,
241             final Attributes atts)
242         throws SAXException {
243 
244         if (snippetStartNodeOverwritten_) {
245             snippetStartNodeOverwritten_ = false;
246             return;
247         }
248         handleCharacters();
249 
250         final String tagLower = StringUtils.toRootLowerCase(localName);
251         if (page_.isParsingHtmlSnippet() && ("html".equals(tagLower) || "body".equals(tagLower))) {
252             // we have to push the current node on the stack to make sure
253             // the endElement call is able to remove a node from the stack
254             stack_.push(currentNode_);
255             return;
256         }
257 
258         if ("head".equals(tagLower)) {
259             if (headParsed_ == HeadParsed.YES || page_.isParsingHtmlSnippet()) {
260                 // we have to push the current node on the stack to make sure
261                 // the endElement call is able to remove a node from the stack
262                 stack_.push(currentNode_);
263                 return;
264             }
265 
266             headParsed_ = lastTagWasSynthesized_ ? HeadParsed.SYNTHESIZED : HeadParsed.YES;
267         }
268 
269         // If we're adding a body element, keep track of any temporary synthetic ones
270         // that we may have had to create earlier (for document.write(), for example).
271         HtmlBody oldBody = null;
272         final boolean isBodyTag = "body".equals(tagLower);
273         if (isBodyTag) {
274             final HtmlBody body = page_.getBody();
275             if (body != null) {
276                 oldBody = body;
277             }
278         }
279 
280         String namespace = namespaceURI == null ? null : namespaceURI.trim();
281         // Add the new node.
282         if (!(page_ instanceof XHtmlPage) && Html.XHTML_NAMESPACE.equals(namespace)) {
283             namespace = null;
284         }
285 
286         ElementFactory factory =
287                 htmlParser_.getElementFactory(page_, namespace, qName, insideSvg_, false);
288 
289         // in xhtml (xml) the namespace decides; an svg element without the svg namespace
290         // (e.g. inheriting the xhtml namespace) is an unknown html element
291         if (page_ instanceof XHtmlPage
292                 && !insideSvg_
293                 && "svg".equals(tagLower)
294                 && !Html.SVG_NAMESPACE.equals(namespace)
295                 && !Html.SVG_NAMESPACE.equals(atts.getValue("xmlns"))) {
296             factory = UnknownElementFactory.INSTANCE;
297         }
298 
299         String elementName = qName;
300         if (factory == HtmlUnitNekoHtmlParser.SVG_FACTORY) {
301             namespace = Html.SVG_NAMESPACE;
302 
303             // the html parser lowercases the name and restores the case of some svg names
304             // (e.g. 'foreignObject'); xml (xhtml) is case sensitive
305             if (!(page_ instanceof XHtmlPage)) {
306                 elementName = SvgElementFactory.adjustTagNameForHtmlParser(qName);
307             }
308         }
309 
310         final DomElement newElement = factory.createElementNS(page_, namespace, elementName, atts);
311         newElement.setStartLocation(locator_.getLineNumber(), locator_.getColumnNumber());
312 
313         // parse can't replace everything as it does not buffer elements while parsing
314         addNodeToRightParent(currentNode_, newElement);
315 
316         if (newElement instanceof HtmlSvg) {
317             insideSvg_ = true;
318         }
319         else if (newElement instanceof HtmlTemplate) {
320             insideTemplate_ = true;
321         }
322 
323         // Forms own elements simply by enclosing source-wise rather than DOM parent-child relationship
324         // Forms without a </form> will keep consuming forever
325         else if (newElement instanceof HtmlForm form) {
326             consumingForm_ = form;
327             formEndingIsAdjusting_ = false;
328         }
329         else if (consumingForm_ != null) {
330             // If the current form enclosed a suitable element
331             if (newElement instanceof SubmittableElement) {
332                 // Let these be owned by the form
333                 if (((HtmlElement) newElement).getEnclosingForm() != consumingForm_) {
334                     ((HtmlElement) newElement).setOwningForm(consumingForm_);
335                 }
336             }
337         }
338 
339         // If we had an old synthetic body, and we just added a real body element, quietly
340         // remove the old body and move its children to the real body element we just added.
341         if (oldBody != null) {
342             oldBody.quietlyRemoveAndMoveChildrenTo(newElement);
343         }
344 
345         if (!insideSvg_ && isBodyTag) {
346             body_ = (HtmlElement) newElement;
347         }
348         else if (createdByJavascript_
349                 && newElement instanceof ScriptElement script
350                 && (!insideTemplate_
351                         || !page_.getWebClient().getBrowserVersion()
352                                 .hasFeature(JS_SCRIPT_IN_TEMPLATE_EXECUTED_ON_ATTACH))) {
353             script.markAsCreatedByDomParser();
354         }
355 
356         // scripts created while parsing the document (or by document.write()) are parser-inserted;
357         // scripts from innerHTML, insertAdjacentHTML(), createContextualFragment()... are not
358         if (!createdByJavascript_
359                 && !page_.isParsingHtmlSnippet()
360                 && newElement instanceof ScriptElement script) {
361             script.markAsParserInserted();
362         }
363 
364         currentNode_ = newElement;
365         stack_.push(currentNode_);
366     }
367 
368     /**
369      * Adds the new node to the right parent that is not necessary the currentNode in case of
370      * malformed HTML code. The method tries to emulate the behavior of Firefox.
371      */
372     private void addNodeToRightParent(final DomNode currentNode, final DomElement newElement) {
373         final String currentNodeName = currentNode.getNodeName();
374         final String newNodeName = newElement.getNodeName();
375 
376         // First ensure table elements are housed correctly
377         if (isTableChild(newNodeName)) {
378             final DomNode parent =
379                     "table".equals(currentNodeName) ? currentNode : findElementOnStack("table");
380             appendChild(parent, newElement);
381             return;
382         }
383         if ("tr".equals(newNodeName)) {
384             final DomNode parent =
385                     isTableChild(currentNodeName) ? currentNode : findElementOnStack("tbody", "thead", "tfoot");
386             appendChild(parent, newElement);
387             return;
388         }
389         if (isTableCell(newNodeName)) {
390             final DomNode parent =
391                     "tr".equals(currentNodeName) ? currentNode : findElementOnStack("tr");
392             appendChild(parent, newElement);
393             return;
394         }
395 
396         // Next ensure non-table elements don't appear in tables
397         if ("table".equals(currentNodeName) || isTableChild(currentNodeName) || "tr".equals(currentNodeName)) {
398             if ("template".equals(newNodeName)) {
399                 currentNode.appendChild(newElement);
400             }
401 
402             // Scripts, forms, and styles are exempt
403             else if (!"colgroup".equals(currentNodeName)
404                     && ("script".equals(newNodeName)
405                         || "form".equals(newNodeName)
406                         || "style".equals(newNodeName))) {
407                 currentNode.appendChild(newElement);
408             }
409 
410             // These are good
411             else if ("col".equals(newNodeName) && "colgroup".equals(currentNodeName)) {
412                 currentNode.appendChild(newElement);
413             }
414             else if ("caption".equals(currentNodeName)) {
415                 currentNode.appendChild(newElement);
416             }
417             else if (newElement instanceof HtmlHiddenInput) {
418                 currentNode.appendChild(newElement);
419             }
420             else {
421                 // Move before the table
422                 final DomNode parent = findElementOnStack("table");
423                 parent.insertBefore(newElement);
424             }
425             return;
426         }
427 
428         if (formEndingIsAdjusting_ && "form".equals(currentNodeName)) {
429             // We cater to HTMLTagBalancer's shortcomings by moving this node out of the <form>
430             appendChild(currentNode.getParentNode(), newElement);
431             return;
432         }
433 
434         // Everything else
435         appendChild(currentNode, newElement);
436     }
437 
438     private DomNode findElementOnStack(final String searchedElementName) {
439         for (final DomNode node : stack_) {
440             if (searchedElementName.equals(node.getNodeName())) {
441                 return node;
442             }
443         }
444 
445         // this is surely wrong but at least it won't throw a NPE
446         return stack_.peek();
447     }
448 
449     private DomNode findElementOnStack(final String... searchedElementNames) {
450         for (final DomNode node : stack_) {
451             for (final String searchedElementName : searchedElementNames) {
452                 if (searchedElementName.equals(node.getNodeName())) {
453                     return node;
454                 }
455             }
456         }
457 
458         // this is surely wrong but at least it won't throw a NPE
459         return stack_.peek();
460     }
461 
462     private static boolean isTableChild(final String nodeName) {
463         if (nodeName == null || nodeName.length() < 5) {
464             return false;
465         }
466 
467         return "thead".equals(nodeName)
468                 || "tbody".equals(nodeName)
469                 || "tfoot".equals(nodeName)
470                 || "caption".equals(nodeName)
471                 || "colgroup".equals(nodeName);
472     }
473 
474     private static boolean isTableCell(final String nodeName) {
475         if (nodeName == null || nodeName.length() != 2) {
476             return false;
477         }
478         return "td".equals(nodeName) || "th".equals(nodeName);
479     }
480 
481     /** {@inheritDoc} */
482     @Override
483     public void endElement(final QName element, final Augmentations augs)
484         throws XNIException {
485         // augs might change so we store only the interesting part
486         lastTagWasSynthesized_ = augs.isSynthesized();
487         super.endElement(element, augs);
488     }
489 
490     /**
491      * {@inheritDoc}
492      */
493     @Override
494     public void endElement(final String namespaceURI, final String localName, final String qName)
495         throws SAXException {
496 
497         final String tagLower = StringUtils.toRootLowerCase(localName);
498 
499         handleCharacters();
500 
501         if (page_.isParsingHtmlSnippet()) {
502             if ("html".equals(tagLower) || "body".equals(tagLower)) {
503                 return;
504             }
505             if (stack_.size() == initialSize_) {
506                 // a <p> inside a <p> is valid for innerHTML processing
507                 // see HTMLParser2Test for more cases
508                 snippetStartNodeOverwritten_ = !StringUtils.equalsChar('p', tagLower);
509                 return;
510             }
511         }
512 
513         if ("svg".equals(tagLower)) {
514             insideSvg_ = false;
515         }
516         else if ("template".equals(tagLower)) {
517             insideTemplate_ = false;
518         }
519 
520         // this only avoids a problem when the stack is empty here
521         // but for this case we made the problem before - the balancing
522         // is broken already
523         if (stack_.isEmpty()) {
524             return;
525         }
526 
527         final DomNode previousNode = stack_.pop(); //remove currentElement from stack
528         previousNode.setEndLocation(locator_.getLineNumber(), locator_.getColumnNumber());
529 
530         if ("form".equals(tagLower) && !lastTagWasSynthesized_) {
531             // We get here if the </form> was on the same DOM tree depth as the <form> that started it,
532             // otherwise HTMLTagBalancer gives us the end through ignoredEndElement()
533             consumingForm_ = null;
534         }
535 
536         if (!stack_.isEmpty()) {
537             currentNode_ = stack_.peek();
538         }
539 
540         final boolean postponed = page_.isParsingInlineHtmlSnippet();
541         previousNode.onAllChildrenAddedToPage(postponed);
542     }
543 
544     /** {@inheritDoc} */
545     @Override
546     public void characters(final char[] ch, final int start, final int length) throws SAXException {
547         characters_.append(ch, start, length);
548     }
549 
550     /** {@inheritDoc} */
551     @Override
552     public void ignorableWhitespace(final char[] ch, final int start, final int length) throws SAXException {
553         characters_.append(ch, start, length);
554     }
555 
556     /**
557      * Picks up the character data accumulated so far and add it to the current element as a text node.
558      */
559     private void handleCharacters() {
560         // make the code easier to read because we remove a nesting level
561         if (characters_.length() == 0) {
562             return;
563         }
564 
565         // Use the normal behavior: append a text node for the accumulated text.
566         final String textValue = characters_.toString();
567         characters_.clear();
568 
569         if (StringUtils.isBlank(textValue)) {
570             appendChild(currentNode_, new DomText(page_, textValue));
571             return;
572         }
573 
574         // malformed HTML: </td>some text</tr> => text comes before the table
575         if (currentNode_ instanceof HtmlTableRow row) {
576             final HtmlTable enclosingTable = row.getEnclosingTable();
577             if (enclosingTable != null) { // may be null when called from Range.createContextualFragment
578                 if (enclosingTable.getPreviousSibling() instanceof DomText domText) {
579                     domText.setTextContent(domText.getWholeText() + textValue);
580                 }
581                 else {
582                     enclosingTable.insertBefore(new DomText(page_, textValue));
583                 }
584             }
585         }
586         else if (currentNode_ instanceof HtmlTable enclosingTable) {
587             if (enclosingTable.getPreviousSibling() instanceof DomText domText) {
588                 domText.setTextContent(domText.getWholeText() + textValue);
589             }
590             else {
591                 enclosingTable.insertBefore(new DomText(page_, textValue));
592             }
593         }
594         else if (currentNode_ instanceof HtmlImage) {
595             currentNode_.getParentNode().appendChild(new DomText(page_, textValue));
596         }
597         else {
598             appendChild(currentNode_, new DomText(page_, textValue));
599         }
600     }
601 
602     /** {@inheritDoc} */
603     @Override
604     public void endDocument() throws SAXException {
605         handleCharacters();
606         if (locator_ != null) {
607             page_.setEndLocation(locator_.getLineNumber(), locator_.getColumnNumber());
608         }
609     }
610 
611     /** {@inheritDoc} */
612     @Override
613     public void startPrefixMapping(final String prefix, final String uri) throws SAXException {
614         // nothing to do
615     }
616 
617     /** {@inheritDoc} */
618     @Override
619     public void endPrefixMapping(final String prefix) throws SAXException {
620         // nothing to do
621     }
622 
623     /** {@inheritDoc} */
624     @Override
625     public void processingInstruction(final String target, final String data) throws SAXException {
626         // nothing to do
627     }
628 
629     /** {@inheritDoc} */
630     @Override
631     public void skippedEntity(final String name) throws SAXException {
632         // nothing to do
633     }
634 
635     // LexicalHandler methods
636 
637     /** {@inheritDoc} */
638     @Override
639     public void comment(final char[] ch, final int start, final int length) {
640         handleCharacters();
641         final String data = new String(ch, start, length);
642         final DomComment comment = new DomComment(page_, data);
643         appendChild(currentNode_, comment);
644     }
645 
646     /** {@inheritDoc} */
647     @Override
648     public void endCDATA() {
649         final String data = characters_.toString();
650         characters_.clear();
651 
652         final DomCDataSection cdataSection = new DomCDataSection(page_, data);
653         appendChild(currentNode_, cdataSection);
654     }
655 
656     /** {@inheritDoc} */
657     @Override
658     public void endDTD() {
659         // nothing to do
660     }
661 
662     /** {@inheritDoc} */
663     @Override
664     public void endEntity(final String name) {
665         // nothing to do
666     }
667 
668     /** {@inheritDoc} */
669     @Override
670     public void startCDATA() {
671         handleCharacters();
672     }
673 
674     /** {@inheritDoc} */
675     @Override
676     public void startDTD(final String name, final String publicId, final String systemId) {
677         final DomDocumentType type = new DomDocumentType(page_, name, publicId, systemId);
678         page_.setDocumentType(type);
679 
680         final Node child;
681         child = type;
682         page_.appendChild(child);
683     }
684 
685     /** {@inheritDoc} */
686     @Override
687     public void startEntity(final String name) {
688         // nothing to do
689     }
690 
691     /**
692      * {@inheritDoc}
693      */
694     @Override
695     public void ignoredEndElement(final QName element, final Augmentations augs) {
696         // HTMLTagBalancer brings us here if </form> was found in the source on a different
697         // DOM tree depth (either above or below) to the <form> that started it
698         if ("form".equals(element.getLocalpart()) && consumingForm_ != null) {
699             consumingForm_ = null;
700 
701             if (findElementOnStack("table", "form") instanceof HtmlTable) {
702                 // The </form> just goes missing for these (really? just tables?)
703             }
704             else {
705                 /*
706                  * This </form> was ignored by HTMLTagBalancer as it generates its own
707                  * </form> at the end of the depth with the starting <form>.
708                  * e.g. This:
709                  * | <form>
710                  * |   <div>
711                  * |     </form> <!--ignored by HTMLTagBalancer-->
712                  * |   </div>
713                  * |   <input>
714                  *
715                  * is turned into:
716                  * | <form>
717                  * |   <div>
718                  * |   </div>
719                  * |   <input>
720                  * | </form> <!--synthesized by HTMLTagBalancer-->
721                  *
722                  * but this isn't suitable for us because </form> shouldn't be ignored but
723                  * rather moved directly behind the tree it's in to instead become:
724                  * | <form>
725                  * |   <div>
726                  * |   </div>
727                  * | </form> <!--moved out of div-->
728                  * | <input> <!--proceeding children are not part of form-->
729                  */
730                 // We cater for this by moving out nodes such as the <input> in the above
731                 // diagram out of the form
732                 formEndingIsAdjusting_ = true;
733             }
734         }
735     }
736 
737     /**
738      * {@inheritDoc}
739      */
740     @Override
741     public void ignoredStartElement(final QName elem, final XMLAttributes attrs, final Augmentations augs) {
742         // when multiple html/body elements are encountered, the attributes of the discarded
743         // elements are used when not previously defined
744         if (attrs != null && body_ != null) {
745             final String lp = elem.getLocalpart();
746             if (lp != null && lp.length() == 4) {
747                 if ("body".equalsIgnoreCase(lp)) {
748                     copyAttributes(body_, attrs);
749                 }
750                 else if ("html".equalsIgnoreCase(lp)) {
751                     final DomNode parent = body_.getParentNode();
752                     if (parent instanceof DomElement element) {
753                         copyAttributes(element, attrs);
754                     }
755                 }
756             }
757         }
758     }
759 
760     private static void copyAttributes(final DomElement to, final XMLAttributes attrs) {
761         final int length = attrs.getLength();
762 
763         for (int i = 0; i < length; i++) {
764             final String attrName = StringUtils.toRootLowerCase(attrs.getLocalName(i));
765             if (to.getAttributes().getNamedItem(attrName) == null) {
766                 to.setAttribute(attrName, attrs.getValue(i));
767                 if (attrName.startsWith("on") && to.getPage().getWebClient().isJavaScriptEngineEnabled()
768                         && to.getScriptableObject() instanceof HTMLBodyElement) {
769                     final HTMLBodyElement jsBody = to.getScriptableObject();
770                     jsBody.createEventHandlerFromAttribute(attrName, attrs.getValue(i));
771                 }
772             }
773         }
774     }
775 
776     /**
777      * {@inheritDoc}
778      */
779     @Override
780     public void parse(final XMLInputSource inputSource) throws XNIException, IOException {
781         final HTMLParserDOMBuilder oldBuilder = page_.getDOMBuilder();
782         page_.setDOMBuilder(this);
783         try {
784             super.parse(inputSource);
785         }
786         finally {
787             page_.setDOMBuilder(oldBuilder);
788         }
789     }
790 
791     private static void appendChild(final DomNode parent, final DomNode child) {
792         if (parent instanceof HtmlTemplate template) {
793             template.getContent().appendChild(child);
794             return;
795         }
796 
797         parent.appendChild(child);
798     }
799 }