Reputation: 59
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
Reputation: 59
We can use two possible ways,
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);
}
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