import ballerina/io;xmlns "http://ballerina.com/aa" as ns0;function main (string[] args) {
    xml x1 = xml `<ns0:book ns0:status="available" count="5"/>`;
    io:println(x1);
    io:println(x1@[ns0:status]);
    string s = x1@["{http://ballerina.com/aa}status"];
    io:println(s);
    io:println(x1@["count"]);
    string attributeName = "count";
    io:println(x1@[attributeName]);
    x1@[ns0:status] = "Not Available";
    io:println(x1@[ns0:status]);
    io:println(x1@);
    map attributeMap = <map>x1@;
    io:println(attributeMap);
    io:println(attributeMap["count"]);
}

XML Attributes

XML elements may have any number of attributes and any number of namespace declarations that apply for that element. In Ballerina, both of these types are treated the same. Attributes are accessed from an XML sequence using the "@" postfix operator.

import ballerina/io;
xmlns "http://ballerina.com/aa" as ns0;
function main (string[] args) {
    xml x1 = xml `<ns0:book ns0:status="available" count="5"/>`;
    io:println(x1);

Create an XML element that has attributes that are bound to a namespace as well as ones that are not.

    io:println(x1@[ns0:status]);

A single attribute that is bound to a namespace can be accessed using its qualified name.

    string s = x1@["{http://ballerina.com/aa}status"];
    io:println(s);

An attribute can also be accessed using the string representation of the qualified name.

    io:println(x1@["count"]);

An attribute that is not bound to a namespace can be accessed using the string representation of the name.

    string attributeName = "count";
    io:println(x1@[attributeName]);

Access an attribute using a dynamic name.

    x1@[ns0:status] = "Not Available";
    io:println(x1@[ns0:status]);

Update an attribute.

    io:println(x1@);

It is possible to get all the attributes at once. However, this cannot be assigned to any variable.

    map attributeMap = <map>x1@;
    io:println(attributeMap);
    io:println(attributeMap["count"]);
}

To assign all the attributes to a variable, it can be cast to a map. Then the values can be accessed one by one using the map access syntax.

$ ballerina run xml-attributes.bal
<ns0:book xmlns:ns0="http://ballerina.com/aa" ns0:status="available" count="5"></ns0:book>
available
available
5
5
Not Available
{"{http://www.w3.org/2000/xmlns/}ns0":"http://ballerina.com/aa", "{http://ballerina.com/aa}status":"Not Available", "count":"5"}
{"{http://www.w3.org/2000/xmlns/}ns0":"http://ballerina.com/aa", "{http://ballerina.com/aa}status":"Not Available", "count":"5"}
5