Java Code Examples for org.dom4j.Attribute

The following examples show how to use org.dom4j.Attribute. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: java-technology-stack   Source File: SelectTagTests.java    License: MIT License 6 votes vote down vote up
private void validateOutput(String output, boolean selected) throws DocumentException {
	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();
	assertEquals("select", rootElement.getName());
	assertEquals("country", rootElement.attribute("name").getValue());

	List children = rootElement.elements();
	assertEquals("Incorrect number of children", 4, children.size());

	Element e = (Element) rootElement.selectSingleNode("option[@value = 'UK']");
	Attribute selectedAttr = e.attribute("selected");
	if (selected) {
		assertTrue(selectedAttr != null && "selected".equals(selectedAttr.getValue()));
	}
	else {
		assertNull(selectedAttr);
	}
}
 
Example 2
Source Project: onos   Source File: XmppStreamOpen.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toXml() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createCompactFormat());
    try {
        out.write("<");
        writer.write(element.getQualifiedName());
        for (Attribute attr : (List<Attribute>) element.attributes()) {
            writer.write(attr);
        }
        writer.write(Namespace.get(this.element.getNamespacePrefix(), this.element.getNamespaceURI()));
        writer.write(Namespace.get("jabber:client"));
        out.write(">");
    } catch (IOException ex) {
        log.info("Error writing XML", ex);
    }
    return out.toString();
}
 
Example 3
Source Project: jeveassets   Source File: Update1To2.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String convertFlag(final Document doc) {
	XPath flagSelector = DocumentHelper.createXPath("/settings/flags/flag");
	List<?> flagResults = flagSelector.selectNodes(doc);
	boolean text = false;
	boolean window = false;
	for (Iterator<?> iter = flagResults.iterator(); iter.hasNext();) {
		Element element = (Element) iter.next();
		Attribute key = element.attribute("key");
		Attribute visible = element.attribute("enabled");
		if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_TEXT")) {
			text = visible.getText().equals("true");
			element.detach();
		}
		if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_WINDOW")) {
			window = visible.getText().equals("true");
			element.detach();
		}
	}
	if (text) {
		return "TEXT";
	}
	if (window) {
		return "WINDOW";
	}
	return "NONE";
}
 
Example 4
Source Project: atlas   Source File: ManifestFileUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static void singleProcess(Document document, String applicationId) {
        List<Node> nodes = document.getRootElement().selectNodes("//provider");
    for (Node node : nodes) {
        Element element = (Element)node;
        String value = element.attributeValue("name");
        if (value.equals(INSTANT_RUN_CONTENTPROVIDER)){
            element.addAttribute("name",ALI_INSTANT_RUN_CONTENTPROVIDER);
            element.addAttribute("authorities",applicationId+"."+ALI_INSTANT_RUN_CONTENTPROVIDER);
            Attribute attribute = element.attribute("multiprocess");
            if (attribute!= null) {
                attribute.setValue("false");
                logger.warn("singleProcess  com.android.tools.ir.server.InstantRunContentProvider.......");
            }

        }

    }

}
 
Example 5
Source Project: gemfirexd-oss   Source File: TestSummaryCreatorTask.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the specified attribute of the node determined by the given xpath.
 * 
 * @param doc      The XML document
 * @param xpath    The xpath selecting the node whose attribute we want
 * @param attrName The name of the attribute
 * @return The attribute value
 */
private String getAttrValue(Document doc, String xpath, String attrName)
{
	Node node = doc.selectSingleNode(xpath);

	if (node instanceof Attribute)
	{
		// we ignore the attribute name then
		return ((Attribute)node).getValue();
	}
	else if (node != null)
	{
		return node.valueOf("@" + attrName);
	}
    else
    {
        return null;
    }
}
 
Example 6
Source Project: atlas   Source File: ManifestFileUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Update the attributes of element
 *
 * @param element
 * @param properties
 */
private static void updateElement(Element element, Map<String, String> properties) {
    for (Map.Entry<String, String> entry : properties.entrySet()) {
        String key = entry.getKey();
        if (key.startsWith("tools:")) {
            continue;
        }
        String keyNoPrefix = key;
        String[] values = StringUtils.split(key, ":");
        if (values.length > 1) {
            keyNoPrefix = values[1];
        }
        if (null == entry.getValue()) {
            continue;
        } else {
            Attribute attribute = element.attribute(keyNoPrefix);
            if (null != attribute) {
                attribute.setValue(entry.getValue());
            } else {
                element.addAttribute(key, entry.getValue());
            }
        }
    }
}
 
Example 7
Source Project: atlas   Source File: ManifestFileUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Update the plug-in's minSdkVersion and targetSdkVersion
 *
 * @param androidManifestFile
 * @throws IOException
 * @throws DocumentException
 */
public static String getVersionName(File androidManifestFile) throws IOException, DocumentException {
    SAXReader reader = new SAXReader();
    String versionName = "";
    if (androidManifestFile.exists()) {
        Document document = reader.read(androidManifestFile);// Read the XML file
        Element root = document.getRootElement();// Get the root node
        if ("manifest".equalsIgnoreCase(root.getName())) {
            List<Attribute> attributes = root.attributes();
            for (Attribute attr : attributes) {
                if (StringUtils.equalsIgnoreCase(attr.getName(), "versionName")) {
                    versionName = attr.getValue();
                }
            }
        }
    }
    return versionName;
}
 
Example 8
Source Project: atlas   Source File: ManifestFileUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String getVersionCode(File androidManifestFile) throws IOException, DocumentException {
    SAXReader reader = new SAXReader();
    String versionCode = "";
    if (androidManifestFile.exists()) {
        Document document = reader.read(androidManifestFile);// Read the XML file
        Element root = document.getRootElement();// Get the root node
        if ("manifest".equalsIgnoreCase(root.getName())) {
            List<Attribute> attributes = root.attributes();
            for (Attribute attr : attributes) {
                if (StringUtils.equalsIgnoreCase(attr.getName(), "versionCode")) {
                    versionCode = attr.getValue();
                }
            }
        }
    }
    return versionCode;
}
 
Example 9
Source Project: unitime   Source File: LowercaseTableNames.java    License: Apache License 2.0 6 votes vote down vote up
protected void writeAttributes(Element element) throws IOException {
    for (int i = 0, size = element.attributeCount(); i < size; i++) {
        Attribute attribute = element.attribute(i);
           char quote = format.getAttributeQuoteCharacter();
           if (element.attributeCount() > 2) {
               writePrintln();
               indent();
               writer.write(format.getIndent());
           } else {
           	writer.write(" ");
           }
           writer.write(attribute.getQualifiedName());
           writer.write("=");
           writer.write(quote);
           writeEscapeAttributeEntities(attribute.getValue());
           writer.write(quote);
    }
}
 
Example 10
private void loadHandles() {
    try {
        SAXReader reader = new SAXReader();
        Document document = reader.read(WeChatFactory.class.getResourceAsStream(config));
        Element list = document.getRootElement();
        List<Element> elements = list.elements();
        for (Element element : elements) {
            if (element.getName().equals("bean")) {
                Attribute className = element.attribute("class");
                log.debug(className.getStringValue());
                handles.add(loadClass(className.getStringValue()));
            }
        }
    } catch (Exception e) {
        log.error("", e);
    }
}
 
Example 11
Source Project: Openfire   Source File: XMLProperties.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Removes the given attribute from the XML document.
 *
 * @param name the property name to lookup - ie, "foo.bar"
 * @param attribute the name of the attribute, ie "id"
 * @return the value of the attribute of the given property or {@code null} if
 *      it did not exist.
 */
public String removeAttribute(String name, String attribute) {
    if (name == null || attribute == null) {
        return null;
    }
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML hierarchy.
    Element element = document.getRootElement();
    for (String child : propName) {
        element = element.element(child);
        if (element == null) {
            // This node doesn't match this part of the property name which
            // indicates this property doesn't exist so return empty array.
            break;
        }
    }
    String result = null;
    if (element != null) {
        // Get the attribute value and then remove the attribute
        Attribute attr = element.attribute(attribute);
        result = attr.getValue();
        element.remove(attr);
    }
    return result;
}
 
Example 12
Source Project: olat   Source File: MaterialParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
*/
  @Override
  public Object parse(final Element element) {
      // assert element.getName().equalsIgnoreCase("material");

      final List materials = element.elements();
      if (materials.size() == 0) {
          return null;
      }

      final Material material = new Material();
      // ATTRIBUTES
      final Attribute label = element.attribute("label");
      if (label != null) {
          material.setLable(label.getValue());
      }

      // ELEMENTS
      for (final Iterator i = materials.iterator(); i.hasNext();) {
          final QTIObject obj = (QTIObject) parserManager.parse((Element) i.next());
          if (obj != null) {
              material.getElements().add(obj);
          }
      }
      return material;
  }
 
Example 13
Source Project: jfinal-api-scaffold   Source File: VersionProperty.java    License: MIT License 6 votes vote down vote up
public void setVersion(ClientType type, String version) {
    Element clientElement = null;
    switch (type) {
        case ANDROID:
            clientElement = getElement("client.android");
            break;
        case IPHONE:
            clientElement = getElement("client.iphone");
            break;
        default:
            return;
    }

    Attribute attribute = clientElement.attribute("default");

    if (attribute != null) {
        attribute.setValue(version);
        saveProperties();
    }
}
 
Example 14
Source Project: renrenpay-android   Source File: XmlToJson.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * org.dom4j.Element 转  com.alibaba.fastjson.JSONObject
 *
 * @param node
 * @return
 */
public static JSONObject elementToJSONObject(Element node) {
    JSONObject result = new JSONObject();
    // 当前节点的名称、文本内容和属性
    List<Attribute> listAttr = node.attributes();// 当前节点的所有属性的list
    for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
        result.put(attr.getName(), attr.getValue());
    }
    // 递归遍历当前节点所有的子节点
    List<Element> listElement = node.elements();// 所有一级子节点的list
    if (!listElement.isEmpty()) {
        for (Element e : listElement) {// 遍历所有一级子节点
            if (e.attributes().isEmpty() && e.elements().isEmpty()) // 判断一级节点是否有属性和子节点
                result.put(e.getName(), e.getTextTrim());// 沒有则将当前节点作为上级节点的属性对待
            else {
                if (!result.containsKey(e.getName())) { // 判断父节点是否存在该一级节点名称的属性
                    if (getKeyCount(e.getName(), listElement) > 1) {
                        result.put(e.getName(), new JSONArray());// 没有则创建
                    } else {
                        result.put(e.getName(), elementToJSONObject(e));// 没有则创建
                        continue;
                    }
                }
                ((JSONArray) result.get(e.getName())).add(elementToJSONObject(e));// 将该一级节点放入该节点名称的属性对应的值中
            }
        }
    }
    return result;
}
 
Example 15
Source Project: olat   Source File: FIBResponse.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets se size to the value stored in this column attribute. It the attribute is null the size is set to the default value
 * 
 * @param i
 */
public void setSizeFromColumns(final Attribute i) {
    if (i == null) {
        size = SIZE_DEFAULT;
    } else {
        final String value = i.getStringValue();
        setSizeFromString(value);
    }
}
 
Example 16
Source Project: ofdrw   Source File: OFDElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 如果属性存在则删除
 *
 * @param name 属性名
 * @return true 删除成功;false 删除失败,可能是由于属性不存在
 */
public boolean removeAttr(String name) {
    Attribute a = this.attribute(name);
    if (a != null) {
        return this.remove(a);
    }
    return false;
}
 
Example 17
public static String getTypeFromXML(Element node) throws MappingException {
	// TODO: handle TypeDefs
	Attribute typeNode = node.attribute( "type" );
	if ( typeNode == null ) typeNode = node.attribute( "id-type" ); // for an any
	if ( typeNode == null ) return null; // we will have to use reflection
	return typeNode.getValue();
}
 
Example 18
Source Project: hop   Source File: XmlInputFieldsImportProgressDialog.java    License: Apache License 2.0 5 votes vote down vote up
private void setAttributeField( Attribute attribute, IProgressMonitor monitor ) {
  // Get Attribute Name
  String attributname = attribute.getName();
  String attributnametxt = cleanString( attribute.getPath() );
  if ( !Utils.isEmpty( attributnametxt ) && !list.contains( attribute.getPath() ) ) {
    nr++;
    monitor.subTask( BaseMessages.getString( PKG, "GetXMLDataXMLInputFieldsImportProgressDialog.Task.FetchFields",
        String.valueOf( nr ) ) );
    monitor.subTask( BaseMessages.getString( PKG, "GetXMLDataXMLInputFieldsImportProgressDialog.Task.AddingField",
        attributname ) );

    RowMetaAndData row = new RowMetaAndData();
    row.addValue( VALUE_NAME, IValueMeta.TYPE_STRING, attributname );
    row.addValue( VALUE_PATH, IValueMeta.TYPE_STRING, attributnametxt );
    row.addValue( VALUE_ELEMENT, IValueMeta.TYPE_STRING, GetXmlDataField.ElementTypeDesc[1] );
    row.addValue( VALUE_RESULT, IValueMeta.TYPE_STRING, GetXmlDataField.ResultTypeDesc[0] );

    // Get attribute value
    String valueAttr = attribute.getText();

    // Try to get the Type

    if ( IsDate( valueAttr ) ) {
      row.addValue( VALUE_TYPE, IValueMeta.TYPE_STRING, "Date" );
      row.addValue( VALUE_FORMAT, IValueMeta.TYPE_STRING, "yyyy/MM/dd" );
    } else if ( IsInteger( valueAttr ) ) {
      row.addValue( VALUE_TYPE, IValueMeta.TYPE_STRING, "Integer" );
      row.addValue( VALUE_FORMAT, IValueMeta.TYPE_STRING, null );
    } else if ( IsNumber( valueAttr ) ) {
      row.addValue( VALUE_TYPE, IValueMeta.TYPE_STRING, "Number" );
      row.addValue( VALUE_FORMAT, IValueMeta.TYPE_STRING, null );
    } else {
      row.addValue( VALUE_TYPE, IValueMeta.TYPE_STRING, "String" );
      row.addValue( VALUE_FORMAT, IValueMeta.TYPE_STRING, null );
    }
    list.add( attribute.getPath() );
  } // end if

}
 
Example 19
Source Project: olat   Source File: QTIHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static float attributeToFloat(final Attribute att) {
    float val = -1;
    if (att != null) {
        String sval = att.getValue();
        sval = sval.trim();
        // assume int value, even so dtd cannot enforce it
        val = Integer.parseInt(sval);
    }
    return val;
}
 
Example 20
public static boolean getAttributeAsBoolean(Element element, String attributeName, boolean defaultValue) {
    Attribute attribute = element.attribute(attributeName);
    if (attribute == null) {
        return defaultValue;
    }

    return "true".equals(attribute.getValue());
}
 
Example 21
Source Project: freeacs   Source File: UnittypeXML.java    License: MIT License 5 votes vote down vote up
public static String getAttr(Node node, String attrName) throws Exception {
  Attribute attr = (Attribute) node.selectSingleNode("@" + attrName);
  if (attr != null) {
    return attr.getValue();
  } else {
    return "";
  }
}
 
Example 22
Source Project: onedev   Source File: VersionedXmlDoc.java    License: MIT License 5 votes vote down vote up
private void marshallElement(HierarchicalStreamWriter writer, Element element) {
	writer.startNode(element.getName());
	for (Attribute attribute: (List<Attribute>)element.attributes())
		writer.addAttribute(attribute.getName(), attribute.getValue());
	if (element.getText().trim().length() != 0)
		writer.setValue(element.getText().trim());
	for (Element child: (List<Element>)element.elements())
		marshallElement(writer, child);
	writer.endNode();
}
 
Example 23
Source Project: mybatis-dalgen   Source File: CfTableRepository.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Attr string.
 *
 * @param e the e
 * @param attr the attr
 * @return the string
 */
private Long attrLong(Element e, String attr) {
    if (e == null || attr == null) {
        return null;
    }
    Attribute attribute = e.attribute(attr);
    if (attribute == null) {
        return null;
    } else {
        return Long.valueOf(attribute.getText());
    }
}
 
Example 24
/**
 * 从单元格Document中获取OLE对象的embedId
 * 
 * @param doc
 * @return
 */
private String extractOleObjectEmbedId(Document doc) {
	Element root = doc.getRootElement();
	Element e = (Element) root.selectSingleNode("//w:object");
	Element oOLEObject = (DefaultElement) e.content().get(1);
	String embedId = ((Attribute) (oOLEObject.attribute("id"))).getValue();
	return embedId;
}
 
Example 25
/**
 * 从单元格Document中获取附件的显示图片的embedId
 * 
 * @param doc
 * @return
 */
private String extractImageEmbedId(Document doc) {
	Element root = doc.getRootElement();
	Element e = (Element) root.selectSingleNode("//w:object");
	Element vShape = (DefaultElement) e.content().get(0);
	Element vImagedata = (Element) vShape.selectSingleNode("//v:imagedata");
	String embedId = ((Attribute) (vImagedata.attribute("id"))).getValue();
	return embedId;
}
 
Example 26
private static ExecuteUpdateResultCheckStyle getResultCheckStyle(Element element, boolean callable) throws MappingException {
	Attribute attr = element.attribute( "check" );
	if ( attr == null ) {
		// use COUNT as the default.  This mimics the old behavior, although
		// NONE might be a better option moving forward in the case of callable
		return ExecuteUpdateResultCheckStyle.COUNT;
	}
	return ExecuteUpdateResultCheckStyle.parse( attr.getValue() );
}
 
Example 27
public void initialise(Element element, NamespacePrefixResolver nspr, PermissionModel permissionModel)
{
    Attribute recipientAttribute = element.attribute(RECIPIENT);
    if (recipientAttribute != null)
    {
        recipient = recipientAttribute.getStringValue();
    }
    else
    {
        recipient = null;
    }

    Attribute accessAttribute = element.attribute(ACCESS);
    if (accessAttribute != null)
    {
        if (accessAttribute.getStringValue().equalsIgnoreCase(ALLOW))
        {
            access = AccessStatus.ALLOWED;
        }
        else if (accessAttribute.getStringValue().equalsIgnoreCase(DENY))
        {
            access = AccessStatus.DENIED;
        }
        else
        {
            throw new PermissionModelException("The default permission must be deny or allow");
        }
    }
    else
    {
        access = AccessStatus.DENIED;
    }
    
    
    Element permissionReferenceElement = element.element(PERMISSION_REFERENCE);
    QName typeQName = QName.createQName(permissionReferenceElement.attributeValue(TYPE), nspr);
    String name = permissionReferenceElement.attributeValue(NAME);
    permissionReference = PermissionReferenceImpl.getPermissionReference(typeQName, name);
}
 
Example 28
public void initialise(Element element, NamespacePrefixResolver nspr, PermissionModel permissionModel)
{
    qname = QName.createQName(element.attributeValue(TYPE), nspr);
    
    Attribute exposeAttribute = element.attribute(EXPOSE);
    if(exposeAttribute != null)
    {
        exposeAll = exposeAttribute.getStringValue().equalsIgnoreCase(EXPOSE_ALL);
    }
    else
    {
        exposeAll = true;
    }
    
    for(Iterator pgit = element.elementIterator(PERMISSION_GROUP); pgit.hasNext(); /**/)
    {
        Element permissionGroupElement = (Element)pgit.next();
        PermissionGroup permissionGroup = new PermissionGroup(qname);
        permissionGroup.initialise(permissionGroupElement, nspr, permissionModel);
        permissionGroups.add(permissionGroup);
    }
    
    for(Iterator pit = element.elementIterator(PERMISSION); pit.hasNext(); /**/)
    {
        Element permissionElement = (Element)pit.next();
        Permission permission = new Permission(qname);
        permission.initialise(permissionElement, nspr, permissionModel);
        permissions.add(permission);
    }
    
}
 
Example 29
public static void bindUnionSubclass(Element node, UnionSubclass unionSubclass,
		Mappings mappings, java.util.Map inheritedMetas) throws MappingException {

	bindClass( node, unionSubclass, mappings, inheritedMetas );
	inheritedMetas = getMetas( node, inheritedMetas, true ); // get meta's from <subclass>

	if ( unionSubclass.getEntityPersisterClass() == null ) {
		unionSubclass.getRootClass().setEntityPersisterClass(
			UnionSubclassEntityPersister.class );
	}

	Attribute schemaNode = node.attribute( "schema" );
	String schema = schemaNode == null ?
			mappings.getSchemaName() : schemaNode.getValue();

	Attribute catalogNode = node.attribute( "catalog" );
	String catalog = catalogNode == null ?
			mappings.getCatalogName() : catalogNode.getValue();

	Table denormalizedSuperTable = unionSubclass.getSuperclass().getTable();
	Table mytable = mappings.addDenormalizedTable(
			schema,
			catalog,
			getClassTableName(unionSubclass, node, schema, catalog, denormalizedSuperTable, mappings ),
	        unionSubclass.isAbstract() != null && unionSubclass.isAbstract().booleanValue(),
			getSubselect( node ),
			denormalizedSuperTable
		);
	unionSubclass.setTable( mytable );

	log.info(
			"Mapping union-subclass: " + unionSubclass.getEntityName() +
			" -> " + unionSubclass.getTable().getName()
		);

	createClassProperties( node, unionSubclass, mappings, inheritedMetas );

}
 
Example 30
public void initialise(Element element, NamespacePrefixResolver nspr, PermissionModel permissionModel)
{
    Attribute authorityAttribute = element.attribute(AUTHORITY);
    if(authorityAttribute != null)
    {
        authority = authorityAttribute.getStringValue();
    }
    Attribute permissionAttribute = element.attribute(PERMISSION);
    if(permissionAttribute != null)
    {
        permissionReference = permissionModel.getPermissionReference(null, permissionAttribute.getStringValue());
    }

}