下面列出了org.w3c.dom.Element#insertBefore ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a new XML Schema element of the given local name
* and insert it as the first child of the given parent node.
*
* @return
* Newly create element.
*/
private Element insertXMLSchemaElement( Element parent, String localName ) {
// use the same prefix as the parent node to avoid modifying
// the namespace binding.
String qname = parent.getTagName();
int idx = qname.indexOf(':');
if(idx==-1) qname = localName;
else qname = qname.substring(0,idx+1)+localName;
Element child = parent.getOwnerDocument().createElementNS( Constants.NS_XSD, qname );
NodeList children = parent.getChildNodes();
if( children.getLength()==0 )
parent.appendChild(child);
else
parent.insertBefore( child, children.item(0) );
return child;
}
/**
* Adds the specified parameters to the xsl template as variables within the alfresco namespace.
*
* @param xsltModel
* the variables to place within the xsl template
* @param xslTemplate
* the xsl template
*/
protected void addParameters(final XSLTemplateModel xsltModel, final Document xslTemplate)
{
final Element docEl = xslTemplate.getDocumentElement();
final String XSL_NS = docEl.getNamespaceURI();
final String XSL_NS_PREFIX = docEl.getPrefix();
for (Map.Entry<QName, Object> e : xsltModel.entrySet())
{
if (ROOT_NAMESPACE.equals(e.getKey()))
{
continue;
}
final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable");
el.setAttribute("name", e.getKey().toPrefixString());
final Object o = e.getValue();
if (o instanceof String || o instanceof Number || o instanceof Boolean)
{
el.appendChild(xslTemplate.createTextNode(o.toString()));
// ALF-15413. Add the variables at the end of the list of children
docEl.insertBefore(el, null);
}
}
}
private static Element maybeImplyHeadElement(Document document, TransformerContext context) {
Element head = getHeadElement(document, context);
if (head == null) {
Element defaultHead = document.createElementNS(TTMLHelper.NAMESPACE_TT, "head");
Element body = getBodyElement(document, context);
try {
Element root = document.getDocumentElement();
if (body != null)
root.insertBefore(defaultHead, body);
else
root.appendChild(defaultHead);
head = defaultHead;
} catch (DOMException e) {
context.getReporter().logError(e);
}
}
return head;
}
/**
* Creates a new XML Schema element of the given local name
* and insert it as the first child of the given parent node.
*
* @return
* Newly create element.
*/
private Element insertXMLSchemaElement( Element parent, String localName ) {
// use the same prefix as the parent node to avoid modifying
// the namespace binding.
String qname = parent.getTagName();
int idx = qname.indexOf(':');
if(idx==-1) qname = localName;
else qname = qname.substring(0,idx+1)+localName;
Element child = parent.getOwnerDocument().createElementNS( Constants.NS_XSD, qname );
NodeList children = parent.getChildNodes();
if( children.getLength()==0 )
parent.appendChild(child);
else
parent.insertBefore( child, children.item(0) );
return child;
}
/**
* Creates a new XML Schema element of the given local name
* and insert it as the first child of the given parent node.
*
* @return
* Newly create element.
*/
private Element insertXMLSchemaElement( Element parent, String localName ) {
// use the same prefix as the parent node to avoid modifying
// the namespace binding.
String qname = parent.getTagName();
int idx = qname.indexOf(':');
if(idx==-1) qname = localName;
else qname = qname.substring(0,idx+1)+localName;
Element child = parent.getOwnerDocument().createElementNS( Constants.NS_XSD, qname );
NodeList children = parent.getChildNodes();
if( children.getLength()==0 )
parent.appendChild(child);
else
parent.insertBefore( child, children.item(0) );
return child;
}
/**
* Creates a new XML Schema element of the given local name
* and insert it as the first child of the given parent node.
*
* @return
* Newly create element.
*/
private Element insertXMLSchemaElement( Element parent, String localName ) {
// use the same prefix as the parent node to avoid modifying
// the namespace binding.
String qname = parent.getTagName();
int idx = qname.indexOf(':');
if(idx==-1) qname = localName;
else qname = qname.substring(0,idx+1)+localName;
Element child = parent.getOwnerDocument().createElementNS( Constants.NS_XSD, qname );
NodeList children = parent.getChildNodes();
if( children.getLength()==0 )
parent.appendChild(child);
else
parent.insertBefore( child, children.item(0) );
return child;
}
private void unsetExcludeEnlistedClasses() throws IOException {
Element puElement = helper.findElement(PERSISTENCE_UNIT_TAG);
NodeList nodes = puElement.getElementsByTagName(EXCLUDE_UNLISTED_CLASSES_TAG);
if (nodes.getLength() > 0) {
helper.setValue((Element) nodes.item(0), "false"); //NOI18N
} else {
puElement.insertBefore(helper.createElement(EXCLUDE_UNLISTED_CLASSES_TAG, "false"), //NOI18N
helper.findElement(PROPERTIES_TAG));
}
}
private void addEntityClasses(Collection<String> classNames) throws IOException {
List<String> toAdd = new ArrayList<String>(classNames);
Element puElement = helper.findElement(PERSISTENCE_UNIT_TAG);
NodeList nodes = puElement.getElementsByTagName(CLASS_TAG);
int length = nodes.getLength();
for (int i = 0; i < length; i++) {
toAdd.remove(helper.getValue((Element) nodes.item(i)));
}
for (String className : toAdd) {
puElement.insertBefore(helper.createElement(CLASS_TAG, className),
helper.findElement(EXCLUDE_UNLISTED_CLASSES_TAG));
}
}
@Override
public void setDocumentVersion(ImmoXmlVersion version) {
try {
Document doc = this.getDocument();
String currentVersion = StringUtils.trimToEmpty(XmlUtils
.newXPath("/io:immoxml/io:uebertragung/@version", doc)
.stringValueOf(doc));
String[] ver = StringUtils.split(currentVersion, "/", 2);
Element node = (Element) XmlUtils
.newXPath("/io:immoxml/io:uebertragung", doc)
.selectSingleNode(doc);
if (node == null) {
Element parentNode = (Element) XmlUtils
.newXPath("/io:immoxml", doc)
.selectSingleNode(doc);
if (parentNode == null) {
LOGGER.warn("Can't find an <immoxml> element in the document!");
return;
}
node = doc.createElement("uebertragung");
parentNode.insertBefore(node, parentNode.getFirstChild());
}
String newVersion = version.toReadableVersion();
if (ver.length > 1) newVersion += "/" + ver[1];
node.setAttribute("version", newVersion);
} catch (JaxenException ex) {
LOGGER.error("Can't evaluate XPath expression!");
LOGGER.error("> " + ex.getLocalizedMessage(), ex);
}
}
public Object getResult(Object existing) {
Document dom = (Document)result.getNode();
Element e = dom.getDocumentElement();
if(existing instanceof Element) {
// merge all the children
Element prev = (Element) existing;
Node anchor = e.getFirstChild();
while(prev.getFirstChild()!=null) {
Node move = prev.getFirstChild();
e.insertBefore(e.getOwnerDocument().adoptNode(move), anchor );
}
}
return e;
}
/**
* Creates a new element with given text: <element>text</element>
* @param element Name of new element tag
* @param text Text that element tag should contain
* @return new element node. (not actually added to document yet)
*/
public Element createElement(String element, String text) {
Element node = document.createElement( element);
if (text != null) {
Node textNode = document.createTextNode( text);
node.insertBefore( textNode, null);
}
return node;
}
public Object getResult(Object existing) {
Document dom = (Document)result.getNode();
Element e = dom.getDocumentElement();
if(existing instanceof Element) {
// merge all the children
Element prev = (Element) existing;
Node anchor = e.getFirstChild();
while(prev.getFirstChild()!=null) {
Node move = prev.getFirstChild();
e.insertBefore(e.getOwnerDocument().adoptNode(move), anchor );
}
}
return e;
}
@Override
protected Element getSemanticElement(Document doc, SymbolContext context) {
// T.L. abstract method used to add data from subclasses
Element e = getLevelElement(doc, context); //SymbolElement.getLevelElement is not supposed to be called
try {
Element l = appendText(doc,"level",Integer.toString(getLevel()));
e.insertBefore(l,e.getFirstChild());
} catch (RuntimeException ee) {
// not sure it is legal for a LevelNode not to have level, debug it!
}
return e;
}
/**
*
* <p>
* insertElementCorrectly
* </p>
*
* @param root
* element representing the < web-app >
* @param toInsert
* element to insert into the web.xml hierarchy.
* @param elementsBefore
* an array of web.xml elements that should be defined before the
* element we want to insert. This order should be the order
* defined by the web.xml's DTD or XSD type definition.
*/
protected static void insertElementCorrectly( Element root, Element toInsert, String[] elementsBefore )
{
NodeList allChildren = root.getChildNodes();
List<String> elementsBeforeList = Arrays.asList(elementsBefore);
Node insertBefore = null;
for (int i = 0; i < allChildren.getLength(); i++)
{
Node node = allChildren.item(i);
if (insertBefore == null)
{
insertBefore = node;
}
if (node.getNodeType() == Node.ELEMENT_NODE)
{
if (elementsBeforeList.contains(node.getNodeName()))
{
insertBefore = null;
}
else
{
break;
}
}
}
if (insertBefore == null)
{
root.appendChild(toInsert);
}
else
{
root.insertBefore(toInsert, insertBefore);
}
}
/**
* Append a child element to the parent at the specified location.
*
* Starting with a valid document, append an element according to the schema
* sequence represented by the <code>order</code>. All existing child elements must be
* include as well as the new element. The existing child element following
* the new child is important, as the element will be 'inserted before', not
* 'inserted after'.
*
* @param parent parent to which the child will be appended
* @param el element to be added
* @param order order of the elements which must be followed
* @throws IllegalArgumentException if the order cannot be followed, either
* a missing existing or new child element is not specified in order
*
* @since 8.4
*/
public static void appendChildElement(Element parent, Element el, String[] order) throws IllegalArgumentException {
List<String> l = Arrays.asList(order);
int index = l.indexOf(el.getLocalName());
// ensure the new new element is contained in the 'order'
if (index == -1) {
throw new IllegalArgumentException("new child element '"+ el.getLocalName() + "' not specified in order " + l); // NOI18N
}
List<Element> elements = findSubElements(parent);
Element insertBefore = null;
for (Element e : elements) {
int index2 = l.indexOf(e.getLocalName());
// ensure that all existing elements are in 'order'
if (index2 == -1) {
throw new IllegalArgumentException("Existing child element '" + e.getLocalName() + "' not specified in order " + l); // NOI18N
}
if (index2 > index) {
insertBefore = e;
break;
}
}
parent.insertBefore(el, insertBefore);
}
public static void addReturnBeforeChild(Element e, Node child) {
if (!ignoreLineBreaks) {
Document doc = e.getOwnerDocument();
e.insertBefore(doc.createTextNode("\n"), child);
}
}
public static Element getOrCreateCallback(Element parent, String name, FacesRegistry registry) {
Element cb = getCallback(parent, name);
if (cb == null) {
cb = XPagesDOMUtil.createElement(parent.getOwnerDocument(), registry, XPagesDOMUtil.getNamespaceUri(), XSP_TAG_CALLBACK);
if (null != name) {
cb.setAttribute(XSP_ATTR_FACETNAME, name);
}
parent.insertBefore(cb, parent.getFirstChild());
}
return cb;
}
public static void addReturnBeforeChild(Element e, Node child) {
if (!ignoreLineBreaks) {
Document doc = e.getOwnerDocument();
e.insertBefore(doc.createTextNode("\n"), child);
}
}
private static boolean updateRawReferenceElement(RawReference ref, Element references) throws IllegalArgumentException {
// Linear search; always keeping references sorted first by foreign project
// name, then by target name.
Element nextRefEl = null;
Iterator<Element> it = XMLUtil.findSubElements(references).iterator();
while (it.hasNext()) {
Element testRefEl = it.next();
RawReference testRef = RawReference.create(testRefEl);
if (testRef.getForeignProjectName().compareTo(ref.getForeignProjectName()) > 0) {
// gone too far, go back
nextRefEl = testRefEl;
break;
}
if (testRef.getForeignProjectName().equals(ref.getForeignProjectName())) {
if (testRef.getID().compareTo(ref.getID()) > 0) {
// again, gone too far, go back
nextRefEl = testRefEl;
break;
}
if (testRef.getID().equals(ref.getID())) {
// Key match, check if it needs to be updated.
if (testRef.getArtifactType().equals(ref.getArtifactType()) &&
testRef.getScriptLocationValue().equals(ref.getScriptLocationValue()) &&
testRef.getProperties().equals(ref.getProperties()) &&
testRef.getTargetName().equals(ref.getTargetName()) &&
testRef.getCleanTargetName().equals(ref.getCleanTargetName())) {
// Match on other fields. Return without changing anything.
return false;
}
// Something needs updating.
// Delete the old ref and set nextRef to the next item in line.
references.removeChild(testRefEl);
if (it.hasNext()) {
nextRefEl = it.next();
} else {
nextRefEl = null;
}
break;
}
}
}
// Need to insert a new record before nextRef.
Element newRefEl = ref.toXml(references.getNamespaceURI(), references.getOwnerDocument());
// Note: OK if nextRefEl == null, that means insert as last child.
references.insertBefore(newRefEl, nextRefEl);
return true;
}
/**
* Adds the element util:message-box in the right place in default.jspx
* layout
*/
private void addMessageBoxInLayout() {
PathResolver pathResolver = projectOperations.getPathResolver();
String defaultJspx = pathResolver.getIdentifier(
LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
"WEB-INF/layouts/default.jspx");
if (!fileManager.exists(defaultJspx)) {
// layouts/default.jspx doesn't exist, so nothing to do
return;
}
InputStream defulatJspxIs = fileManager.getInputStream(defaultJspx);
Document defaultJspxXml;
try {
defaultJspxXml = XmlUtils.getDocumentBuilder().parse(defulatJspxIs);
}
catch (Exception ex) {
throw new IllegalStateException("Could not open default.jspx file",
ex);
}
Element lsHtml = defaultJspxXml.getDocumentElement();
// Set dialog tag lib as attribute in html element
lsHtml.setAttribute("xmlns:dialog",
"urn:jsptagdir:/WEB-INF/tags/dialog/modal");
Element messageBoxElement = DomUtils.findFirstElementByName(
"dialog:message-box", lsHtml);
if (messageBoxElement == null) {
Element divMain = XmlUtils.findFirstElement(
"/html/body/div/div[@id='main']", lsHtml);
Element insertAttributeBodyElement = XmlUtils.findFirstElement(
"/html/body/div/div/insertAttribute[@name='body']", lsHtml);
Element messageBox = new XmlElementBuilder("dialog:message-box",
defaultJspxXml).build();
divMain.insertBefore(messageBox, insertAttributeBodyElement);
}
writeToDiskIfNecessary(defaultJspx, defaultJspxXml.getDocumentElement());
}