import ballerina/io;function main (string[] args) {
xml x1 = xml `<book>
<name>Sherlock Holmes</name>
<author>Sir Arthur Conan Doyle</author>
<!--Price: $10-->
</book>`;
io:println(x1);
xmlns "http://ballerina.com/";
xmlns "http://ballerina.com/aa" as ns0;
xml x2 = xml `<book ns0:status="available">
<ns0:name>Sherlock Holmes</ns0:name>
<author>Sir Arthur Conan Doyle</author>
<!--Price: $10-->
</book>`;
io:println(x2);
string rootTag = "{http://ballerina.com/aa}newBook";
string title = "(Sir)"; xml x3 = xml `<{{rootTag}}>
<name>Sherlock Holmes</name>
<author>{{title}} Arthur Conan Doyle</author>
<!--Price: ${{ 40 / 5 + 4 }}-->
</{{rootTag}}>`;
io:println(x3);
}
XML LiteralBallerina allows you to define XML as part of the language and syntactically validate it. It can insert expressions into the XML literal that pass values dynamically during runtime. |
|
import ballerina/io;
|
|
function main (string[] args) {
|
|
xml x1 = xml `<book>
<name>Sherlock Holmes</name>
<author>Sir Arthur Conan Doyle</author>
<!--Price: $10-->
</book>`;
io:println(x1);
|
A complex XML defined using the literal syntax, having nested elements of different types. |
xmlns "http://ballerina.com/";
xmlns "http://ballerina.com/aa" as ns0;
|
Defined namespaces. These are visible to all the XML literals defined from here onwards. |
xml x2 = xml `<book ns0:status="available">
<ns0:name>Sherlock Holmes</ns0:name>
<author>Sir Arthur Conan Doyle</author>
<!--Price: $10-->
</book>`;
io:println(x2);
|
Create an XML element. Previously defined namespaces will get added to the element. The defined prefixes can be applied to elements and attributes inside the element. |
string rootTag = "{http://ballerina.com/aa}newBook";
string title = "(Sir)";
|
XML interpolated with expressions using the ‘{{}}’ notation. The expression can be a previously defined variable, arithmetic expressions, or even a function call. These expressions get evaluated during runtime. |
xml x3 = xml `<{{rootTag}}>
<name>Sherlock Holmes</name>
<author>{{title}} Arthur Conan Doyle</author>
<!--Price: ${{ 40 / 5 + 4 }}-->
</{{rootTag}}>`;
io:println(x3);
}
|
|
$ ballerina run xml-literal.bal
<book>
<name>Sherlock Holmes</name>
<author>Sir Arthur Conan Doyle</author>
<!--Price: $10-->
</book>
<book xmlns="http://ballerina.com/" xmlns:ns0="http://ballerina.com/aa" ns0:status="available">
<ns0:name>Sherlock Holmes</ns0:name>
<author>Sir Arthur Conan Doyle</author>
<!--Price: $10-->
</book>
<ns0:newBook xmlns:ns0="http://ballerina.com/aa" xmlns="http://ballerina.com/">
<name>Sherlock Holmes</name>
<author>(Sir) Arthur Conan Doyle</author>
<!--Price: $ 12-->
</ns0:newBook>
|
|