Prakanth
Prakanth

Reputation: 59

How to get xml attribute to the ballerina record?

Consider the following record,

type Person record {
    string name;
    int age;
};

The xml samples is,

<Person>
 <name value="karen"/>
 <age>18</age>
</Person>

How to assign the attribute value to the field name?

Upvotes: 0

Views: 32

Answers (1)

Prakanth
Prakanth

Reputation: 59

We can use two possible ways,

  1. We can simply manipulate the xml according to the expected record type as below.
    import ballerina/xmldata;
    import ballerina/io;
    
    type Person record {
        string name;
        int age;
    };
    
    public function main() returns error? {
        xml xmlVal = xml `<Person>
                <name value="karen"/>
                <age>18</age>
            </Person>`;
        xml personXml = xml `<Person>${
                            from xml child in xmlVal.children()
                            // or ensuring type to be `xml:Element` if all items are elements
                            // let xml:Element elemChild = check child.ensureType()
                            where child is xml:Element
                            let string|error name = child.value
                            select name is string ?
                                xml:createElement(child.getName(), children = xml `${name}`) :
                                child
                            }</Person>`;
        Person person = check xmldata:fromXml(personXml);
        io:println(person);
    }
  1. Convert to a separate compatible record type and manipulate the field according to the expected Person record type.
    import ballerina/xmldata;
    import ballerina/io;
    
    type Person record {
        string name;
        int age;
    };
    
    @xmldata:Name {
        value: "Person"
    }
    type PersonTemp record {|
        record {|
            @xmldata:Attribute
            string value;
        |} name;
        int age;
    |};
    
    public function main() returns error? {
        xml xmlVal = xml `<Person>
                <name value="karen"/>
                <age>18</age>
            </Person>`;
        PersonTemp person = check xmldata:fromXml(xmlVal);
        Person p = transformPerson(person);
        io:println(p);
    }
    
    function transformPerson(PersonTemp p) returns Person {
        return {
            name: p.name.value,
            age: p.age
        };
    }

Upvotes: 0

Related Questions