The node class is an ancestor of all XML node types.
Example:
<li>Fred</li><li>Wilma</li>val nodes: NodeSeq = items
* * Element properties
To work with the property keys and values of an element, you can use the Attraibutes property.
val elem = <a href="http://www.baidu.com">The Baidu Site</a>val url = elem.attributes("href")
The above call outputs a sequence of nodes, not a string.
If you are sure that there are no unresolved entities in your attribute, you can simply call the text method to convert the node sequence to a string:
"elem.attributes("href").text//如果不存在这个属性,就会返回null.
inline-expression
You can include Scala code in the XML literal to dynamically calculate the element content.
<ul><li>{items(0)}</li><li>{items(1)}</li></ul>//每段代码都会被求值,其结果会被拼接到XML树中。
Not only can you include Scala code in the XML literal, but the embedded Scala code can also continue to contain XML word variables.
<ul>{for (i <- items) yield <li>{i}</li>}</ul>
Above this is the set of Scala code in XML, and then sets the XML.
Using an expression in an attribute
<img src={makeURL(fileName)}/>//makeURL函数将会返回一个字符串,而该字符串将会成为属性值。
An inline code block can also produce a sequence of nodes. If you want to include entity references or atoms in a property, look at this:
<a id={new Atom(1... />
If the inline code block returns null or None, the property is not set.
if"TODO"else... />
Class-XPath expression
The NodeSeq class provides a method similar to that of the XPath in/and//operators.
Because//represents a comment, it is not a valid operator.
Scala uses \ and \ instead.
<dl><dt>Java</dt><dd><dt>Scala</dt><dd>Odersky</dd></dl>val language = list \ "dt"
Wildcard characters can match any element:
"body""_""li"//找到所有的li元素。"img"// “\\”操作符可以定位任何深度的后代。
A string starting with @ can locate the property.
"@alt"//返回给顶点的alt属性
The result of \ or \ is a sequence of nodes. It could be a single node, but unless you're pretty sure, you should traverse it instead of just treating it as a single node:
for"img") 处理n
If you call text only for the result of \ or \, all the text in the result sequence will be threaded together:
(<img src="test.jpg"/><img src="hello.jpg"/> \\"@src").text//将会返回字符串“test.jpghello.jpg”
Pattern matching
You can use XML literals in pattern-matching expressions.
node match { ... ...}
If node is an IMG element with any attributes but no descendants, the first match succeeds.
To match any number of items, as follows:
...
To handle wildcards, you can also use variable names, and the content that is successfully matched will be bound to that variable.
<li>{child}</li> => child.text
To match a text node, you can do the following:
case <li>{Text(itemitem
To help the node sequence to a variable, the following:
case <li>{children @ _*}</li> =>foryield c
modifying elements and attributes
The XML nodes and sequence of nodes in Scala are immutable. If you are editing a node, you must create a copy, give the changes you need to make, and then copy the parts that are not explicitly modified.
val list = <ul><li>Fred</li><li>Wilma</li></ul>val list2 = list.copy(lavel = "ol")//上面代码会创建一个list的拷贝,将标签ul修改为ol
XML transformations
The XML class library provides a Ruletranfonner class that can apply one or more rewriterule instances to a node and its descendants.
valnew RewriteRule { overridedefmatch { case"ol") }}
After that, you can use the following command to transform an XML tree:
val transformed = new RuleTransformer(rule1).transform(root)
You can give multiple rules in the Ruletransormer constructor:
val transformer = new RuleTransformer(rule1, rule2, rule3)
Loading and saving
To load an XML document from a file, call the LoadFile method of the XML object:
import scala.xml.XMLval root = XML.loadFile("myfile.xml")
You can also load from Java.io.InputStream or Java.io.Reader or URL:
val root2 = XML.load(new FileInputStream("myfile.xtml"))val root3 = XML.load(new InputStreamReader(new FileInputStream("myfile.xml", "UTF-8")))val root4 = XML.load(new URL("http://www.baidu.com/index.html"))
Scala also offers an additional parser:
import scala.xml.parsing.ConstructingParserimport java.io.Fileval parser = ConstructingParser.fromFile(new File("myfile.xml"), perserveWS = true)val doc = parser.documentval root = doc.docElem//注意ConstructingParser返回一个类型为Document的节点,调用其docElem方法可以取得文档根节点。
Name space
In XML, namespaces are used to avoid name collisions, similar to the concept of packages in Java.
An XML namespace is a URI (usually also a URL).
Welcome to the Scala discussion QQ group 212859367, and Lianle together to discuss learning!
Learn Scala-xml with Lianle.