1

Hi I'm having a problem getting the value of an attribute in an xml file using namespaces.

<module name="ietf-inet-types" xmlns="urn:ietf:params:xml:ns:yang:yin:1" xmlns:inet="urn:ietf:params:xml:ns:yang:ietf-inet-types"> <namespace uri="urn:ietf:params:xml:ns:yang:ietf-inet-types"/> <prefix value="inet"/> </module> 

I want to get "inet" as the result of my xpath. I used this link Xpath to select value of sibling attribute with namespace as a reference and came up with:

$xml->xpath('/n:module/n:prefix/@n:value'); 

where n is the namespace prefix. However I'm getting an empty array as a result, what exactly am I doing wrong here?

Update: Heres some of the php code I'm using to retrieve the value.

//gets the namespace from the model $xpathNamespace = getXpathNamespace($domxml); $xml = simplexml_load_string($domxml->saveXML()); $xml->registerXPathNamespace("n", $xpathNamespace); print_r($xml->xpath('/n:module/n:prefix/@n:value')); 

2 Answers 2

1

In XML attributes without a namespace tag (eg. value) are not in any namespace: default namespace does not apply to attributes.

Try the XPath:

/n:module/n:prefix/@value 
Sign up to request clarification or add additional context in comments.

4 Comments

Hi I tried that but got the same result as when I use the xpath /n:module/n:prefix/. The result is: Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [value] => inet ) ) )
@olliejjc16 In which case, could you update the question with the code you are using (specifically how you are associating n with the namespace in the XPath processor: but make it a complete but minimal re-create).
Thanks lads for the help, got it sorted between the information you both provided!
1

Ok here's the solution thanks to both Richard and har07 combined for the help. To access the value of the prefix I used the below xpath suggested by Richard. From the information in the link posted by har7 I accessed the first element in the array and converted it to a string and I got the value "inet". Heres the code:

$prefix = $xml->xpath('/n:module/n:prefix/@value'); print_r((string)$prefix[0]); 

Thanks to both for the help!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.