Ballerina: undefined function 'getItemType' in type 'xml'

116 Views Asked by At
import ballerina/io;
import ballerina/lang.'xml;
public function main() returns error? {


    xml x = xml `<book>Hamlet</book><book>Macbeth</book>`;
    xml mappedXml = x.map(function (xml xmlContent) returns xml =>
    xml `<book kind="play">${xmlContent.children()}</book>` 
    );

    string y = x.getItemType();
    io:println(y);
}

This does not compile and gives the error of

ERROR [main.bal:(11:18,11:29)] undefined function 'getItemType' in type 'xml'
error: compilation contains errors

I have tried many forms of xmls to do this, but any method i did not find the xml getItemType. Anyone knows the answer?

I am expecting how to compile, this code and how to use getItemType() method in order to work on the my project on developing the an intergration for the ballerina language.

2

There are 2 best solutions below

0
On

For the ballerina xml type we don't have a method called getItemType. Thats why you are getting this compile time error. If you want to access the specific segments of this xml sequence you can do as below example.

import ballerina/io;

public function main() returns error? {
    xml x = xml `<book>Hamlet</book><book>Macbeth</book>`;
    xml mappedXml = x.map(function (xml xmlContent) returns xml =>
    xml `<book kind="play">${xmlContent.children()}</book>` 
    );

    foreach var item in mappedXml.<book> {
        io:println(item); // print the xml Element
        io:println(item.data()); // print the data item in the element
        io:println(item.kind); // print the arrtibute named 'kind' in the element
    }
}

For further reference you can find these BBEs expaling accesing and navigating on xml values. XML value access

XML value navigation

0
On

getItemType() was a function available with pre-1.0.0 versions of Ballerina. Ballerina 1.0.0 introduced language libraries instead with an extensive and improved set of functions associated with values of the basic types.

The lang library for XML also introduced builtin subtypes to represent the different XML content singletons - xml:Element, xml:Comment, xml:ProcessingInstruction, and xml:Text. You can use the is check with these types to identify the kind of an XML singleton.

In case the is checks aren't sufficient and behaviour similar to the previous getItemType() function is required, you could do something like

enum ItemType {
    ELEMENT,
    COMMENT,
    TEXT,
    PI
}

function getItemType(xml x) returns ItemType? {
    if x.length() != 1 {
        return ();
    }

    xml item = x.get(0);
    
    if item is xml:Element {
        return ELEMENT;
    }
    if item is xml:Comment {
        return COMMENT;
    }
    if item is xml:ProcessingInstruction {
        return PI;
    }
    return TEXT;
}
xml x = xml `<book>Hamlet</book>`;
ItemType? y = getItemType(x);
io:println(y); // ELEMENT

Also see API docs of the ballerina/lang.xml lang library and Ballerina XML examples.