17

In the example below, how do I access the attribute 'id' once it has a namespace prefix?

scala> val ns = <foo id="bar"></foo>    
ns: scala.xml.Elem = <foo id="bar"></foo>

scala> ns \ "@id"                   
res15: scala.xml.NodeSeq = bar

Above works fine. According to the docs below should work but it doesn't.

scala> val ns = <foo xsi:id="bar"></foo>
ns: scala.xml.Elem = <foo xsi:id="bar"></foo>

scala> ns \ "@{xsi}id"                   
res16: scala.xml.NodeSeq = NodeSeq()

All on Scala 2.8.0.final

Cheers

Answer: It seems without an xlmns in the xml you can't access the attribute. So for the above example to work it needs to be inside an xlm namespace. e.g.:

scala> val xml = <parent xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <foo xsi:id="bar"></foo></parent>
xml: scala.xml.Elem = <parent xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <foo xsi:id="bar"></foo></parent>

scala> xml \ "foo" \ "@{http://www.w3.org/2001/XMLSchema-instance}id"
res3: scala.xml.NodeSeq = bar
2
  • 1
    From the Scala API (NodeSeq): ns \ "@{uri}foo" to get the prefixed attribute "pre:foo" whose prefix "pre" is resolved to the namespace "uri". But ns \ "@{xsi}id" is not working :( Commented Feb 22, 2011 at 15:12
  • Thanks Thomas, I somehow missed that in the docs. I've updated the example to show how it still doesn't work even when following the API correctly. Commented Feb 22, 2011 at 15:33

2 Answers 2

14

Take a look at this post: Accessing XML attributes with namespaces.

It looks like the uri that is referred to in:

ns \ "@{uri}foo"

Refers to the part after the equal sign. This works:

scala> val ns = <foo xmlns:id="bar" id:hi="fooMe"></foo>
ns: scala.xml.Elem = <foo id:hi="fooMe" xmlns:id="bar"></foo>

scala> ns \ "@{bar}hi"
res9: scala.xml.NodeSeq = fooMe

So I think the first thing after foo is to define your URL and namespace, and then to define the attribute, so if you want to get the attribute "bar", maybe something like this:

scala> val ns = <foo xmlns:myNameSpace="id" myNameSpace:id="bar"></foo>
ns: scala.xml.Elem = <foo myNameSpace:id="bar" xmlns:myNameSpace="id"></foo>

scala> ns \ "@{id}id"
res10: scala.xml.NodeSeq = bar

Although I'm not sure about the correctness of reusing the URI as attribute name.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi CaffiendFrog. You're right, I have to use the xmlns as part of the pattern. Thank you.
You might want to mention ns \@ "{id}id" giving the String value of the attribute.
4

You can use

ns.attributes.head.asAttrMap("xsi:id")

1 Comment

Thanks! It runs nice if you work with single node and do not have the namespace definition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.