Search code examples
xmlxml-parsingattributeskeywordballerina

How to access attributes of an xml element which are keywords in ballerina?


Consider the below code segment written in ballerina.

xml xmlHello = xml `<para id="greeting">Hello</para>`;
string id = check xmlHello.id;
io:println(id);

In the above scenario, the output will be greeting.

Now consider the below.

xml xmlHello = xml `<para type="singlePara">Hello</para>`;
string paraType = check xmlHello.type;
io:println(paraType);

This gives an invalid token error since type is a keyword in Ballerina. How to access the type attribute in this scenario?


Solution

  • You can use the single quote to escape the keywords.

    string paraType = check xmlHello.'type;