I try to get a child from an Element in a XML context in Google Apps Script. The XML Element looks like this:
<wsKlasgroep>
<p_persoon>39579</p_persoon>
...
</wsKlasgroep>
So I try to get the p_persoon text object using:
indiviual_class.getChild("p_persoon")
Which results in a null. So I tried to loop all children, showing all the names and values:
let classes = xmlResult.getChildren();
classes.forEach(indiviual_class => {
Logger.log(indiviual_class.getChild("p_persoon")); //null
indiviual_class.getChildren().forEach(child => {
Logger.log(child.getName() ": " child.getText());//p_persoon: 39579
});
});
Why can't I access a Child by it's name, while the data seems to be right? I'm clearly missing something here.
Thanks for any help
CodePudding user response:
In the case of <wsKlasgroep><p_persoon>39579</p_persoon>...</wsKlasgroep>
you show, the root is <wsKlasgroep>
. If xmlResult
is the root, the length of indiviual_class.getChildren()
is 0
. From this situation, I thought that in your situation, the sample XML might be <sample><wsKlasgroep><p_persoon>39579</p_persoon></wsKlasgroep></sample>
. But, unfortunately, I cannot know your actual XML data. So, in this answer, from your showing script and your showing XML, I would like to propose an answer.
Answer 1:
In this answer, const xml = "<wsKlasgroep><p_persoon>39579</p_persoon></wsKlasgroep>";
is used. And the value of 39579
is retrieved.
function sample1() {
const xml = "<wsKlasgroep><p_persoon>39579</p_persoon></wsKlasgroep>";
const root = XmlService.parse(xml).getRootElement();
const value = root.getChild("p_persoon", root.getNamespace()).getValue();
console.log(value)
}
When this script is run, you can see 39579
in the log.
Answer 2:
In this answer, const xml = "<sample><wsKlasgroep><p_persoon>39579</p_persoon></wsKlasgroep></sample>";
is used. And the value of 39579
is retrieved.
In this sample, getChildren()
is used as you are using in your showing script.
function sample2() {
const xml = "<sample><wsKlasgroep><p_persoon>39579</p_persoon></wsKlasgroep></sample>";
const root = XmlService.parse(xml).getRootElement();
const ns = root.getNamespace();
root.getChildren().forEach(indiviual_class => {
const value = indiviual_class.getChild("p_persoon", ns).getValue();
console.log(value)
});
}
In this sample, getChildren()
is not used.
function sample3() {
const xml = "<sample><wsKlasgroep><p_persoon>39579</p_persoon></wsKlasgroep></sample>";
const root = XmlService.parse(xml).getRootElement();
const ns = root.getNamespace();
const value = root.getChild("wsKlasgroep", ns).getChild("p_persoon", ns).getValue();
console.log(value)
}
When this script is run, you can see 39579
in the log.
Note:
- In this case,
root.getNamespace()
is used as the namespace. But, unfortunately, I cannot know your actual XML data and your whole script. So, if the above modifications were not useful, can you provide more sample XML and script? By this, I would like to confirm your actual situation.