Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method returns NodeBuffer instead of Elem and that violates the type checking rule

Tags:

xml

scala

There are 2 methods, both return xml:

 def method1 = 
   <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope>
      <soap:Header>
        {Elem(....)}
      </soap:Header>
    </soap:Envelope>

 def method2 = 
  <someXml>
    //.......
  </someXml>

And there is one more method which gets Elem:

def method3(a: Elem) = //....

val xml1 = method1
val xml2 = method2

method3(xml1) //error
method3(xml2) //ok

It says method1 returns NodeBuffer and it can't accept it, whereas method2 returns Elem and that's perfectly fine.

Why is that? What do I do about it?

like image 801
Incerteza Avatar asked Jul 09 '26 21:07

Incerteza


1 Answers

scala> def method1 = <?xml version="1.0" encoding="utf-8"?><root />
method1: scala.xml.NodeBuffer

In method1 you are trying to create not a xml with a XML declaration, but 2 Nodes: Processing instruction (scala type ProcInstr) and Elem:

scala> <?abc attr1="v1" attr2="v2" ?>
res0: scala.xml.ProcInstr = <?abc attr1="v1" attr2="v2" ?>

Sequence of 2 nods gives you a collection of nodes - NodeBuffer:

scala> <a/><b/>
res0: scala.xml.NodeBuffer = ArrayBuffer(<a/>, <b/>)

Actually you can't use processing instruction xml manually:

scala> <?xml version="1.0" encoding="utf-8"?>
java.lang.IllegalArgumentException: xml is reserved

Just remove it.

If you need XML declaration in serialized version you should use XML.write or XML.save with xmlDecl = true:

import xml.XML
val myXml = <root />
val writer = new java.io.StringWriter
XML.write(writer, myXml, "utf-8", xmlDecl = true, doctype = null)
writer.toString
// <?xml version='1.0' encoding='utf-8'?>
// <root/>
like image 51
senia Avatar answered Jul 13 '26 08:07

senia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!