Access nested attributes using SimpleXML
I have been working on writing a function to edit an XML document using just SimpleXML. This is a sample of the XML file I am working with today:
Accessing the children of Employees was the easy part. Create the SimpleXML object and the nodes become properties of the object.
The trouble I had was in accessing the attributes of the child nodes. I was thinking about it in terms of the attributes being arrays, when in fact they were a child simpleXML object! After some reading about the SimpleXML object I came this solution for accessing the user type for my "employee".
What this does is select the child node of Employee called "Access_Info". From there the attributes() method is called which returns a new simpleXML object to work with. So what was once hard is now as easy as the first example. Once we have the SimpleXML object we can then access the values quite easily.
Conclusion
So what did I take away from this experience? Well for starters just because it looks complicated, doesn't make it so. The biggest issue I had was that I was being returned SimpleXML objects and I wasn't sure how to access the information. It became easier to work with once I could visually see that objects can nests inside one another. Just because the SimpleXML object was a child of another object didn't mean I couldn't use the same methods on either. Essentially what I learned was that when given a situation that I am unsure of, the best way to work through it is to assess my options.
Social Media