Some docbook elements need to be wrapped up so they can be properly transformed by the docbook XSL.

@param xmlDoc
549679
public static void wrapForRendering(final Document xmlDoc) {
        // Some topics need to be wrapped up to be rendered properly
        final String documentElementNodeName = xmlDoc.getDocumentElement().getNodeName();
        if (documentElementNodeName.equals("authorgroup") || documentElementNodeName.equals("legalnotice")) {
            final Element currentChild = xmlDoc.createElement(documentElementNodeName);

            xmlDoc.renameNode(xmlDoc.getDocumentElement(), xmlDoc.getNamespaceURI(), "book");
            final Element bookInfo = xmlDoc.createElement("bookinfo");
            xmlDoc.getDocumentElement().appendChild(bookInfo);
            bookInfo.appendChild(currentChild);

            final NodeList existingChildren = xmlDoc.getDocumentElement().getChildNodes();
            for (int childIndex = 0; childIndex < existingChildren.getLength(); ++childIndex) {
                final Node child = existingChildren.item(childIndex);
                if (child != bookInfo) {
                    currentChild.appendChild(child);
                }
            }
        }
    }
933944
public void buildFieldDoc(XMLNode node, Content memberDetailsTree) {
        if (writer == null) {
            return;
        }
        int size = fields.size();
        if (size > 0) {
            Content fieldDetailsTree = writer.getFieldDetailsTreeHeader(
                    classDoc, memberDetailsTree);
            for (currentFieldIndex = 0; currentFieldIndex < size;
                    currentFieldIndex++) {
                Content fieldDocTree = writer.getFieldDocTreeHeader(
                        (FieldDoc) fields.get(currentFieldIndex),
                        fieldDetailsTree);
                buildChildren(node, fieldDocTree);
                fieldDetailsTree.addContent(writer.getFieldDoc(
                        fieldDocTree, (currentFieldIndex == size - 1)));
            }
            memberDetailsTree.addContent(
                    writer.getFieldDetails(fieldDetailsTree));
        }
    }
743758
def setListDoc(self, doc):
        
        if doc is None: doc__o = None
        else: doc__o = doc._o
        libxml2mod.xmlSetListDoc(self._o, doc__o)
606463
private static Document createXML(String root, boolean useNamespace) {
		try {
			org.w3c.dom.Document doc = getDocumentBuilder(null, useNamespace).newDocument();
			doc.appendChild(doc.createElement(root));
			return new DocumentImpl(doc);
		} catch (Exception e) {
			throw new DomException(e);
		}
	}
374170
public static boolean start(RootDoc rootDoc) {
        final MarkdownTaglets markdownTaglets = MarkdownTaglets.instance();
        Options options = new Options();
        String[][] forwardedOptions = options.load(rootDoc.options(), rootDoc);
        if ( forwardedOptions == null ) {
            return false;
        }
        MarkdownDoclet doclet = new MarkdownDoclet(options, rootDoc);
        markdownTaglets.setDocErrorReporter(doclet);
        doclet.process();
        if ( doclet.isError() ) {
            return false;
        }
        RootDocWrapper rootDocWrapper = new RootDocWrapper(rootDoc, forwardedOptions);
        if ( options.isHighlightEnabled() ) {
            // find the footer option
            int i = 0;
            for ( ; i < rootDocWrapper.options().length; i++ ) {
                if ( rootDocWrapper.options()[i][0].equals("-footer") ) {
                    rootDocWrapper.options()[i][1] += HIGHLIGHT_JS_HTML;
                    break;
                }
            }
            if ( i >= rootDocWrapper.options().length ) {
                rootDocWrapper.appendOption("-footer", HIGHLIGHT_JS_HTML);
            }
        }
        return Standard.start(rootDocWrapper) && doclet.postProcess();
    }
1025839
function(doc, nodes, selector, after) {
        var parent = module.exports.resolveParent(doc, selector);
        if (!parent) {
            //Try to create the parent recursively if necessary
            try {
                var parentToCreate = et.XML('<' + path.basename(selector) + '>'),
                    parentSelector = path.dirname(selector);

                this.graftXML(doc, [parentToCreate], parentSelector);
            } catch (e) {
                return false;
            }
            parent = module.exports.resolveParent(doc, selector);
            if (!parent) return false;
        }

        nodes.forEach(function (node) {
            // check if child is unique first
            if (uniqueChild(node, parent)) {
                var children = parent.getchildren();
                var insertIdx = after ? findInsertIdx(children, after) : children.length;

                //TODO: replace with parent.insert after the bug in ElementTree is fixed
                parent.getchildren().splice(insertIdx, 0, node);
            }
        });

        return true;
    }
120866
public static void saveXML(Document document, File file) {
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = null;
		try {

			xmlWriter = new XMLWriter(new FileOutputStream(file), format);
			xmlWriter.write(document);

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (xmlWriter != null) {
				try {
					xmlWriter.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
387962
private void includeXmlContent(final XIncludeAttributes xIncludeAttributes)
            throws XIncludeFatalException, XIncludeResourceException
    {
        try
        {
            settingLanguage();
            final SAXSource source = buildingXIncludeSource(xIncludeAttributes);
            final TreeInfo docInfo = this.context.getConfiguration().getProcessor().getUnderlyingConfiguration()
                    .buildDocumentTree(source);
            final XdmNode node = new XdmNode(docInfo.getRootNode());
            startingInjectXInclude();
            injectingXInclude(xIncludeAttributes, source, node);
        }
        catch (final XPointerResourceException e)
        {
            throw new XIncludeResourceException(e.getMessage());
        }
        catch (final XPointerException e)
        {
            throw new XIncludeFatalException(e.getMessage());
        }
        catch (final XPathException e)
        {
            if (e.getCause() instanceof XIncludeFatalException)
            {
                throw (XIncludeFatalException) e.getCause();
            }
            else
            {
                throw new XIncludeFatalException(e.getMessage());
            }
        }
        finally
        {
            if (isInjectingXInclude())
            {
                endingInjectXInclude();
            }
        }
    }
115670
protected void adoptElement(DomXmlElement elementToAdopt) {
    Document document = this.domElement.getOwnerDocument();
    Element element = elementToAdopt.domElement;

    if (!document.equals(element.getOwnerDocument())) {
      Node node = document.adoptNode(element);
      if (node == null) {
        throw LOG.unableToAdoptElement(elementToAdopt);
      }
    }
  }
1042209
public void fromXML(Document domdoc) throws DocumentException
    {
        this.encoding = domdoc.getXMLEncoding();

        Element rootElement = domdoc.getRootElement();

        this.reference = readDocumentReference(domdoc);

        this.locale = rootElement.attributeValue("locale");
        if (this.locale == null) {
            // Fallback on old <language> element
            this.locale = readElement(rootElement, "language");
        }

        this.defaultLanguage = readElement(rootElement, "defaultLanguage");
        this.creator = readElement(rootElement, "creator");
        this.author = readElement(rootElement, AUTHOR_TAG);
        this.contentAuthor = readElement(rootElement, "contentAuthor");
        this.version = readElement(rootElement, "version");
        this.parent = readElement(rootElement, "parent");
        this.comment = readElement(rootElement, "comment");
        this.minorEdit = readElement(rootElement, "minorEdit");
        this.attachmentData = readAttachmentData(rootElement);
        this.isHidden = Boolean.parseBoolean(readElement(rootElement, "hidden"));
        this.title = readElement(rootElement, "title");
        this.syntaxId = readElement(rootElement, "syntaxId");
        this.content = readElement(rootElement, "content");

        this.datePresent = isElementPresent(rootElement, "date");
        this.contentUpdateDatePresent = isElementPresent(rootElement, "contentUpdateDate");
        this.creationDatePresent = isElementPresent(rootElement, "creationDate");
        this.attachmentDatePresent = rootElement.selectSingleNode("//attachment/date") != null;

        // Does this document contain a XWiki.TranslationDocumentClass xobject?
        if (!rootElement.selectNodes("//object/className[text() = 'XWiki.TranslationDocumentClass']").isEmpty()) {
            this.containsTranslations = true;
            // Record the visibility
            for (Node node : rootElement
                .selectNodes("//object/className[text() = 'XWiki.TranslationDocumentClass']/../property/scope")) {
                this.translationVisibilities.add(node.getStringValue());
            }
        }
    }
56616
def save_xml(self, doc, element):
        ''''''
        element.setAttributeNS(RTS_NS, RTS_NS_S + 'name', self.name)
        if self.data:
            element.setAttributeNS(RTS_NS, RTS_NS_S + 'data', self.data)
1067725
public void writeEndDocument() throws XMLStreamException {
		try {
			checkPendingATEvents();
			encoder.encodeEndDocument();
			encoder.flush();
		} catch (Exception e) {
			throw new XMLStreamException(e.getLocalizedMessage(), e);
		}
	}
203659
private void loadXMLResource(final File file) {

		final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		// Ignore comments in the XML file
		docBuilderFactory.setIgnoringComments(true);
		docBuilderFactory.setNamespaceAware(true);

		try {

			final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
			Document doc = null;
			Element root = null;

			doc = builder.parse(file);

			if (doc == null) {
				LOG.warn("Cannot load configuration: doc is null");
				return;
			}

			root = doc.getDocumentElement();
			if (root == null) {
				LOG.warn("Cannot load configuration: root is null");
				return;
			}

			if (!"configuration".equals(root.getNodeName())) {
				LOG.warn("Cannot load configuration: unknown element " + root.getNodeName());
				return;
			}

			final NodeList props = root.getChildNodes();
			int propNumber = -1;

			synchronized (this.confData) {

				for (int i = 0; i < props.getLength(); i++) {

					final Node propNode = props.item(i);
					String key = null;
					String value = null;

					// Ignore text at this point
					if (propNode instanceof Text) {
						continue;
					}

					if (!(propNode instanceof Element)) {
						LOG.warn("Error while reading configuration: " + propNode.getNodeName()
							+ " is not of type element");
						continue;
					}

					Element property = (Element) propNode;
					if (!"property".equals(property.getNodeName())) {
						LOG.warn("Error while reading configuration: unknown element " + property.getNodeName());
						continue;
					}

					propNumber++;
					final NodeList propChildren = property.getChildNodes();
					if (propChildren == null) {
						LOG.warn("Error while reading configuration: property has no children, skipping...");
						continue;
					}

					for (int j = 0; j < propChildren.getLength(); j++) {

						final Node propChild = propChildren.item(j);
						if (propChild instanceof Element) {
							if ("key".equals(propChild.getNodeName())) {
								if (propChild.getChildNodes() != null) {
									if (propChild.getChildNodes().getLength() == 1) {
										if (propChild.getChildNodes().item(0) instanceof Text) {
											final Text t = (Text) propChild.getChildNodes().item(0);
											key = t.getTextContent();
										}
									}
								}
							}

							if ("value".equals(propChild.getNodeName())) {
								if (propChild.getChildNodes() != null) {
									if (propChild.getChildNodes().getLength() == 1) {
										if (propChild.getChildNodes().item(0) instanceof Text) {
											final Text t = (Text) propChild.getChildNodes().item(0);
											value = t.getTextContent();
										}
									}
								}
							}
						}
					}

					if (key != null && value != null) {
						// Put key, value pair into the map
						LOG.debug("Loading configuration property: " + key + ", " + value);
						this.confData.put(key, value);
					} else {
						LOG.warn("Error while reading configuration: Cannot read property " + propNumber);
						continue;
					}
				}
			}

		} catch (ParserConfigurationException e) {
			LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
		} catch (IOException e) {
			LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
		} catch (SAXException e) {
			LOG.warn("Cannot load configuration: " + StringUtils.stringifyException(e));
		}
	}
1096299
function xmlImportNode(doc, node) {
  if (node.nodeType == DOM_TEXT_NODE) {
    return domCreateTextNode(doc, node.nodeValue);

  } else if (node.nodeType == DOM_CDATA_SECTION_NODE) {
    return domCreateCDATASection(doc, node.nodeValue);

  } else if (node.nodeType == DOM_ELEMENT_NODE) {
    var newNode = domCreateElement(doc, node.nodeName);
    for (var i = 0; i < node.attributes.length; ++i) {
      var an = node.attributes[i];
      var name = an.nodeName;
      var value = an.nodeValue;
      domSetAttribute(newNode, name, value);
    }

    for (var c = node.firstChild; c; c = c.nextSibling) {
      var cn = arguments.callee(doc, c);
      domAppendChild(newNode, cn);
    }

    return newNode;

  } else {
    return domCreateComment(doc, node.nodeName);
  }
}
475525
private void writeXmlDocument(String path, Document doc) throws IOException {
    zip.putNextEntry(new ZipEntry(path));
    try {
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(zip);
      transformer.transform(source, result);
    }
    catch (TransformerException ex) {
      throw new IOException("Failed to generate XML: " + ex.getMessage(), ex);
    }
    finally {
      zip.closeEntry();
    }
  }
830965
def write_xml_document(self, document):
        
        self._out.write(ET.tostring(document))
        self._out.flush()
350797
public final String rewriteXml(
        Node xmlDoc,
        String aloneTags[],
        boolean outputXmlHeader
    ) {
        try {
            StringWriter sOut = new StringWriter();
            rewriteXml(
                sOut,
                xmlDoc,
                aloneTags,
                outputXmlHeader
            );

            return sOut.toString();
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }