Preprocesses occurrences of Argument within the root.

    Argument XML values reference other values within the document by name. The
    referenced value does not contain a switch. This function will add the
    switch associated with the argument.
550629
def __preprocess_arguments(root):
    
    # Set the flags to require a value
    flags = ','.join(vsflags(VSFlags.UserValueRequired))

    # Search through the arguments
    arguments = root.getElementsByTagName('Argument')

    for argument in arguments:
        reference = __get_attribute(argument, 'Property')
        found = None

        # Look for the argument within the root's children
        for child in root.childNodes:
            # Ignore Text nodes
            if isinstance(child, Element):
                name = __get_attribute(child, 'Name')

                if name == reference:
                    found = child
                    break

        if found is not None:
            logging.info('Found property named %s', reference)
            # Get the associated switch
            switch = __get_attribute(argument.parentNode, 'Switch')

            # See if there is already a switch associated with the element.
            if __get_attribute(found, 'Switch'):
                logging.debug('Copying node %s', reference)
                clone = found.cloneNode(True)
                root.insertBefore(clone, found)
                found = clone

            found.setAttribute('Switch', switch)
            found.setAttribute('Flags', flags)
        else:
            logging.warning('Could not find property named %s', reference)
739790
public Element append(String name, String value) {
		Element child = document.createElementNS(XCAL_NS, name);
		child.setTextContent(value);
		element.appendChild(child);
		return child;
	}
587079
def newDocProp(self, name, value):
        
        ret = libxml2mod.xmlNewDocProp(self._o, name, value)
        if ret is None:raise treeError('xmlNewDocProp() failed')
        __tmp = xmlAttr(_obj=ret)
        return __tmp
1069429
function(rootNode, name, value) {
			var arr = [],
				x = 0,
				i,
				out = [];

			arr = this.getNodesByAttribute(rootNode, name);
			if(arr) {
				i = arr.length;
				while(x < i) {
					if(this.hasAttributeValue(arr[x], name, value)) {
						out.push(arr[x]);
					}
					x++;
				}
			}
			return out;
		}
1240953
def parse(self, arguments):
    
    if not isinstance(arguments, list):
      # Default value may be a list of values.  Most other arguments
      # will not be, so convert them into a single-item list to make
      # processing simpler below.
      arguments = [arguments]

    if self.present:
      # keep a backup reference to list of previously supplied option values
      values = self.value
    else:
      # "erase" the defaults with an empty list
      values = []

    for item in arguments:
      # have Flag superclass parse argument, overwriting self.value reference
      Flag.Parse(self, item)  # also increments self.present
      values.append(self.value)

    # put list of option values back in the 'value' attribute
    self.value = values
742050
def __with_argument(node, value):
    """"""
    arguments = node.getElementsByTagName('Argument')

    if arguments:
        logging.debug('Found argument within %s', value['name'])
        value['flags'] = vsflags(VSFlags.UserValueIgnored, VSFlags.Continue)
660206
protected void addNewField(Item item, String values) {
        if(logger.isDebugEnabled()) {
            logger.debug("Tagging item with field: " + newField + " and value: " + values);
        }
        Document document = item.getDescriptorDom();
        if(document != null) {
            Element root = document.getRootElement();
            if(root != null) {
                for(String value : values.split(",")) {
                    Element newElement = root.addElement(newField);
                    newElement.setText(value);
                }
            }
        }
    }
1139273
def xmlGenPrecursorList(precursorList):
    
    numEntries = len(precursorList)
    xmlPrecursorList = ETREE.Element('precursorList',
                                     {'count': str(numEntries)}
                                     )
    for precursor in precursorList:
        #Note: no attributes for external referencing supported
        precursorAttrib = {}
        if precursor['spectrumRef'] is not None:
            precursorAttrib.update({'spectrumRef': precursor['spectrumRef']})
        xmlPrecursor = ETREE.Element('precursor', precursorAttrib)

        #Add isolationWindow element
        if precursor['isolationWindow'] is not None:
            xmlIsolationWindow = ETREE.Element('isolationWindow')
            maspy.xml.xmlAddParams(xmlIsolationWindow,
                                   precursor['isolationWindow']
                                   )
            xmlPrecursor.append(xmlIsolationWindow)

        #Add selectedIonList element
        numSelectedIons = len(precursor['selectedIonList'])
        if numSelectedIons > 0:
            xmlSelectedIonList = ETREE.Element('selectedIonList',
                                               {'count': str(numSelectedIons)}
                                               )
            for selectedIon in precursor['selectedIonList']:
                xmlSelectedIon = ETREE.Element('selectedIon')
                maspy.xml.xmlAddParams(xmlSelectedIon, selectedIon)
                xmlSelectedIonList.append(xmlSelectedIon)
            xmlPrecursor.append(xmlSelectedIonList)

        #Add activation element
        xmlActivation = ETREE.Element('activation')
        maspy.xml.xmlAddParams(xmlActivation, precursor['activation'])
        xmlPrecursor.append(xmlActivation)


        xmlPrecursorList.append(xmlPrecursor)
    return xmlPrecursorList
257496
function appendMeArgs (e, args /* null/undefined, string, node, or array-like of nodes incl.
			live NodeList */, attrsP) {
  if (args == null) ;
  else if (typeof args == 'string')
    e.appendChild(e.ownerDocument.createTextNode(args));
  else if (args.nodeType) e.appendChild(args);
  else {
    if (args.constructor != Array) args = F.slice(args);	// for live NodeList
    F.iter(function (x) {
      e.appendChild(x);
    }, args);
  }
  return M.setAttrs(e, attrsP);
}
624796
XMLName toXMLNameOrIndex(Context cx, Object value)
    {
        XMLName result;

        if (value instanceof XMLName) {
            result = (XMLName)value;
        } else if (value instanceof String) {
            String str = (String)value;
            long test = ScriptRuntime.testUint32String(str);
            if (test >= 0) {
                ScriptRuntime.storeUint32Result(cx, test);
                result = null;
            } else {
                result = toXMLNameFromString(cx, str);
            }
        } else if (value instanceof Number) {
            double d = ((Number)value).doubleValue();
            long l = (long)d;
            if (l == d && 0 <= l && l <= 0xFFFFFFFFL) {
                ScriptRuntime.storeUint32Result(cx, l);
                result = null;
            } else {
                throw badXMLName(value);
            }
        } else if (value instanceof QName) {
            QName qname = (QName)value;
            String uri = qname.uri();
            boolean number = false;
            result = null;
            if (uri != null && uri.length() == 0) {
                // Only in this case qname.toString() can resemble uint32
                long test = ScriptRuntime.testUint32String(uri);
                if (test >= 0) {
                    ScriptRuntime.storeUint32Result(cx, test);
                    number = true;
                }
            }
            if (!number) {
                result = XMLName.formProperty(uri, qname.localName());
            }
        } else if (value instanceof Boolean
                   || value == Undefined.instance
                   || value == null)
        {
            throw badXMLName(value);
        } else {
            String str = ScriptRuntime.toString(value);
            long test = ScriptRuntime.testUint32String(str);
            if (test >= 0) {
                ScriptRuntime.storeUint32Result(cx, test);
                result = null;
            } else {
                result = toXMLNameFromString(cx, str);
            }
        }

        return result;
    }
1123721
def _visit_immediate_value_references(value, visitor):
    ''' 

    '''
    if isinstance(value, HasProps):
        for attr in value.properties_with_refs():
            child = getattr(value, attr)
            _visit_value_and_its_immediate_references(child, visitor)
    else:
        _visit_value_and_its_immediate_references(value, visitor)
37904
protected void updatePluginConfiguration(PluginConfiguration value, String xmlTag, Counter counter,
            Element element)
   {
      boolean shouldExist = value != null;
      Element root = updateElement(counter, element, xmlTag, shouldExist);
      if (shouldExist)
      {
         Counter innerCount = new Counter(counter.getDepth() + 1);
         updatePluginManagement(value.getPluginManagement(), "pluginManagement", innerCount, root);
         iteratePlugin(innerCount, root, value.getPlugins(), "plugins", "plugin");
      }
   }
714758
public static void addNSdeclarations(Element source, Element target)
            throws Exception {
        NamedNodeMap sourceAttributes = source.getAttributes();
        Attr attribute;
        String attributeName;
        for (int i = 0; i <= sourceAttributes.getLength() - 1; i++) {
            attribute = (Attr) sourceAttributes.item(i);
            attributeName = attribute.getName();
            if (attributeName.startsWith("xmlns")
                    && !attributeName.startsWith("xmlns:soap-env")) {
                // System.out.println("XMLNS:" +
                // attributeName+":"+attribute.getValue());
                target.setAttribute(attributeName, attribute.getValue());
            }
        }
    }
311490
private void putElement(final String elemName, final Attributes atts, final boolean removeConref) throws SAXException {
        //parameter boolean removeConref specifies whether to remove
        //conref information like @conref @conaction in current element
        //when copying it to pushcontent. True means remove and false means
        //not remove.
        final Set<String> namespaces = new HashSet<>();
        try {
            pushcontentWriter.writeStartElement(elemName);
            for (int index = 0; index < atts.getLength(); index++) {
                final String name = atts.getQName(index);
                if (!removeConref ||
                        !ATTRIBUTE_NAME_CONREF.equals(name) && !ATTRIBUTE_NAME_CONACTION.equals(name)) {
                    String value = atts.getValue(index);
                    if (ATTRIBUTE_NAME_HREF.equals(name) || ATTRIBUTE_NAME_CONREF.equals(name)) {
                        // adjust href for pushbefore and replace
                        value = replaceURL(value);
                    }
                    final int offset = atts.getQName(index).indexOf(":");
                    final String prefix = offset != -1 ? atts.getQName(index).substring(0, offset) : "";
                    if (!namespaces.contains(prefix)) {
                        namespaces.add(prefix);
                        if (!prefix.isEmpty()) {
                            pushcontentWriter.writeNamespace(prefix, atts.getURI(index));
                        }
                    }
                    pushcontentWriter.writeAttribute(prefix, atts.getURI(index), atts.getLocalName(index), value);
                }
            }
            //id attribute should only be added to the starting element
            //which dosen't have id attribute set
            if (ATTR_CONACTION_VALUE_PUSHREPLACE.equals(pushType) &&
                    atts.getValue(ATTRIBUTE_NAME_ID) == null &&
                    level == 1) {
                final String fragment = target.getFragment();
                if (fragment == null) {
                    //if there is no '#' in target string, report error
                    logger.error(MessageUtils.getMessage("DOTJ041E", target.toString()).toString());
                } else {
                    String id;
                    //has element id
                    if (fragment.contains(SLASH)) {
                        id = fragment.substring(fragment.lastIndexOf(SLASH) + 1);
                    } else {
                        id = fragment;
                    }
                    //add id attribute
                    pushcontentWriter.writeAttribute(ATTRIBUTE_NAME_ID, id);
                }
            }
        } catch (final XMLStreamException e) {
            throw new SAXException(e);
        }
    }
1339627
def handle_data(self, data):
        '''
            
        '''
        if data:
            inTag = self._inTag
            if len(inTag) > 0:
                if inTag[-1].tagName not in PRESERVE_CONTENTS_TAGS:
                    data = data.replace('\t', ' ').strip('\r\n')
                    if data.startswith(' '):
                        data = ' ' + data.lstrip()
                    if data.endswith(' '):
                        data = data.rstrip() + ' '
                inTag[-1].appendText(data)
            elif data.strip():
                # Must be text prior to or after root node
                raise MultipleRootNodeException()
307846
def update(self, **kwargs):
        
        """
        for key, value in kwargs.items():
            helper = helpers.CAST_DICT.get(type(value), str)
            tag = self._get_aliases().get(key, key)

            elements = list(self._xml.iterchildren(tag=tag))
            if elements:
                for element in elements:
                    element.text = helper(value)
            else:
                element = etree.Element(key)
                element.text = helper(value)
                self._xml.append(element)
                self._aliases = None
182317
private void internalizeDocument(Document document) throws ParseException {
    init();

    // temporarily remove the database listeners
    List<IDatabaseListener> tmpListeners = new ArrayList<>(listeners);
    listeners.clear();

    Hashtable<String, String> keyMap = new Hashtable<>();

    try {
      Element rootElement = document.getRootElement();
      List<Attribute> rootAttrs = rootElement.getAttributes();

      // extract the master language and put all other root element
      // attributes aside
      for (Attribute attribute : rootAttrs) {
        if (MASTER_LANGUAGE_ATTRIBUTE_NAME.equals(attribute.getName())) {
          masterLanguage = attribute.getValue();
        } else {
          additionalRootAttrs.add(attribute);
        }
      }

      // store additional namespaces. the xsi namespace is used for the attribute xsi:noSchemaNamespaceLocation
      for (Object namespace : rootElement.getAdditionalNamespaces()) {
        // The list is not type save, therefore a cast is done
        if (namespace instanceof Namespace) {
          additionalNamespaces.add((Namespace) namespace);
        } else {
          throw new RuntimeException("Namespace List contains Objects that are not of type Namespace");
        }
      }

      if (masterLanguage == null) {
        // since we cannot determine the line numbers in this methods
        // we pass 0 to occuring ParseExceptions
        throw new ParseException("Master language missing.", 0);
      }

      List<Element> textList = rootElement.getChildren(TEXT_ELEMENT_NAME);

      // the validation in here is kind of unnecessary when the xsd is used for validation.
      // however the xsd validation was added later and it cant hurt to doublecheck some things, there might be cases
      // where the xsd cannot be used
      for (Element textElement : textList) {
        String key = textElement.getAttributeValue(KEY_ATTRIBUTE_NAME);
        if (key == null) {
          throw new ParseException("No key found for text.",
              ((LineNumberElement) textElement).getStartLine());
        }

        if (keyMap.containsKey(key)) {
          parseWarnings.add(new ParseWarning("Duplicate key: " + key,
              ((LineNumberElement) textElement).getStartLine()));
        } else {
          keyMap.put(key, "");
        }

        String context = textElement.getChildText(CONTEXT_ELEMENT_NAME);
        if (context == null) {
          throw new ParseException("No context found for key \"" + key + "\".",
              ((LineNumberElement) textElement).getStartLine());
        }

        ITextNode textNode = new XMLTextNode(key, context);
        addTextNode(textNode);

        List<Element> valueList = textElement.getChildren(VALUE_ELEMENT_NAME);
        for (Element valueElement : valueList) {
          String language = valueElement.getAttributeValue(LANGUAGE_ATTRIBUTE_NAME);
          if (language == null) {
            throw new ParseException("No language found for value of key \"" + key + "\".",
                ((LineNumberElement) valueElement).getStartLine());
          }
          String statusName = valueElement.getAttributeValue(STATUS_ATTRIBUTE_NAME);
          Status status = Status.valueOf(statusName);
          if (status == null) {
            throw new ParseException("Invalid status for key \"" + key + "\": " + statusName,
                ((LineNumberElement) valueElement).getStartLine());
          }
          String value = valueElement.getText();
          textNode.addValueNode(new XMLValueNode(language, status, value));
        }
      }
    } finally {
      listeners.addAll(tmpListeners);
    }
  }