Not yet rated

Problem

I need to access attribute key of QName instance , to know this name related to element or to attribute.

Solution

I have created class based on Proxy methods, to do this.

Detailed explanation

 

QName instance received from XML attribute has the same properties as QName instance received from XML element and you can't know by this two is it from element or from attribute. But if you will pass it back to XML element it will return correct node even if it will have attribute and element with the same name inside.

var xml:XML = <root node="attribute">
    <node><![CDATA[element]]</node>
</root>;

var name:QName = xml.@node.name();
trace(name); // node
trace(xml[name]); // attribute

var name:QName = xml.node.name();
trace(name); // node
trace(xml[name]); // element


As you can see, no difference outside and some difference inside. QName instance has some invisible key that contains isAttribute/isElement value. Before I used separated collections and wrapper objects to save this value, but some time ago I remembered that Proxy class has flash_proxy::isAttribute method, that can get this value for me. And I created new class especially for this purposes - to GET and SET this value. It is called aw.utils.QNameUtils and very simple to use it:

var xml:XML = <root node="attribute">
<node><![CDATA[element]]>
</node>
</root>;

var name:QName = xml.@node.name();
trace(name); // node
trace(xml[name]); // attribute
trace(QNameUtils.isAttribute(name)); // true
name = QNameUtils.setAttribute(name, false);
trace(xml[name]); // element

var name:QName = xml.node.name();
trace(name); // node
trace(xml[name]); // element
trace(QNameUtils.isAttribute(name)); // false
name = QNameUtils.setAttribute(name, true);
trace(xml[name]); // attribute

name = QNameUtils.create('', 'node', true)
trace(xml[name]); // attribute


Methods of this class:

  • isAttribute(name:*):Boolean - Get attribute key value
  • setAttribute(name:*, isAttribute:Boolean=true):QName - Set attribute key value
  • parse(value:String):QName - Create QName intance from string
  • create(uri:*=null, localName:*=null, attribute:Boolean=false):QName - Create QName instance

You can download it as ZIP package.

aw.utils.QNameUtils.zip
[Source code of aw.utils.QNameUtils class]

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes