Bekerja dengan XML di Groovy

1. Perkenalan

Groovy menyediakan sejumlah besar metode yang didedikasikan untuk melintasi dan memanipulasi konten XML.

Dalam tutorial ini, kami akan mendemonstrasikan cara menambahkan, mengedit, atau menghapus elemen dari XML di Groovy menggunakan berbagai pendekatan. Kami juga akan menunjukkan cara membuat struktur XML dari awal .

2. Mendefinisikan Model

Mari tentukan struktur XML di direktori sumber daya yang akan kita gunakan di seluruh contoh kita:

  First steps in Java  Siena Kerr  2018-12-01   Dockerize your SpringBoot application  Jonas Lugo  2018-12-01   SpringBoot tutorial  Daniele Ferguson  2018-06-12   Java 12 insights  Siena Kerr  2018-07-22  

Dan membacanya menjadi variabel InputStream :

def xmlFile = getClass().getResourceAsStream("articles.xml")

3. XmlParser

Mari mulai menjelajahi aliran ini dengan kelas XmlParser .

3.1. Bacaan

Membaca dan mengurai file XML mungkin merupakan operasi XML paling umum yang harus dilakukan pengembang. The XmlParser menyediakan antarmuka yang sangat mudah dimaksudkan untuk persis bahwa:

def articles = new XmlParser().parse(xmlFile)

Pada titik ini, kita dapat mengakses atribut dan nilai struktur XML menggunakan ekspresi GPath.

Sekarang mari kita terapkan tes sederhana menggunakan Spock untuk memeriksa apakah objek artikel kita sudah benar:

def "Should read XML file properly"() { given: "XML file" when: "Using XmlParser to read file" def articles = new XmlParser().parse(xmlFile) then: "Xml is loaded properly" articles.'*'.size() == 4 articles.article[0].author.firstname.text() == "Siena" articles.article[2].'release-date'.text() == "2018-06-12" articles.article[3].title.text() == "Java 12 insights" articles.article.find { it.author.'@id'.text() == "3" }.author.firstname.text() == "Daniele" }

Untuk memahami cara mengakses nilai XML dan cara menggunakan ekspresi GPath, mari kita fokus sejenak pada struktur internal hasil operasi XmlParser # parse .

The artikel objek adalah sebuah contoh dari groovy.util.Node. Setiap Node terdiri dari nama, peta atribut, nilai, dan induk (yang bisa berupa null atau Node lain ) .

Dalam kasus kami, nilai artikel adalah turunan groovy.util.NodeList , yang merupakan kelas pembungkus untuk kumpulan Node s. The NodeList memperluas java.util.ArrayList kelas, yang menyediakan ekstraksi elemen dengan indeks. Untuk mendapatkan nilai string dari sebuah Node, kami menggunakan groovy.util.Node # text ().

Dalam contoh di atas, kami memperkenalkan beberapa ekspresi GPath:

  • Articles.article [0] .author.firstname - dapatkan nama depan penulis untuk artikel pertama - Articles.article [n] akan langsung mengakses artikel ke- n
  • '*' - dapatkan daftar anak artikel - itu setara dengan groovy.util.Node # children ()
  • author.'@id ' - dapatkan atribut id dari elemen penulis - author.'@attributeName' mengakses nilai atribut dengan namanya (yang setara adalah: penulis ['@ id'] dan [email dilindungi] )

3.2. Menambahkan Node

Mirip dengan contoh sebelumnya, mari kita membaca konten XML menjadi variabel terlebih dahulu. Ini akan memungkinkan kita untuk menentukan node baru dan menambahkannya ke daftar artikel kita menggunakan groovy.util.Node # append.

Sekarang mari menerapkan tes yang membuktikan maksud kita:

def "Should add node to existing xml using NodeBuilder"() { given: "XML object" def articles = new XmlParser().parse(xmlFile) when: "Adding node to xml" def articleNode = new NodeBuilder().article(id: '5') { title('Traversing XML in the nutshell') author { firstname('Martin') lastname('Schmidt') } 'release-date'('2019-05-18') } articles.append(articleNode) then: "Node is added to xml properly" articles.'*'.size() == 5 articles.article[4].title.text() == "Traversing XML in the nutshell" }

Seperti yang bisa kita lihat pada contoh di atas, prosesnya cukup mudah.

Mari perhatikan juga bahwa kita menggunakan groovy.util.NodeBuilder, yang merupakan alternatif yang rapi untuk menggunakan konstruktor Node untuk definisi Node kita .

3.3. Memodifikasi Node

Kami juga dapat mengubah nilai node menggunakan XmlParser . Untuk melakukannya, mari sekali lagi mengurai konten file XML. Selanjutnya, kita dapat mengedit node konten dengan mengubah bidang nilai objek Node .

Mari kita ingat bahwa saat XmlParser menggunakan ekspresi GPath, kita selalu mengambil instance NodeList, jadi untuk memodifikasi elemen pertama (dan satu-satunya), kita harus mengaksesnya menggunakan indeksnya.

Mari kita periksa asumsi kita dengan menulis tes singkat:

def "Should modify node"() { given: "XML object" def articles = new XmlParser().parse(xmlFile) when: "Changing value of one of the nodes" articles.article.each { it.'release-date'[0].value = "2019-05-18" } then: "XML is updated" articles.article.findAll { it.'release-date'.text() != "2019-05-18" }.isEmpty() }

Dalam contoh di atas, kami juga menggunakan Groovy Collections API untuk melintasi NodeList .

3.4. Mengganti Node

Selanjutnya, mari kita lihat cara mengganti seluruh node daripada hanya memodifikasi salah satu nilainya.

Similarly to adding a new element, we'll use the NodeBuilder for the Node definition and then replace one of the existing nodes within it using groovy.util.Node#replaceNode:

def "Should replace node"() { given: "XML object" def articles = new XmlParser().parse(xmlFile) when: "Adding node to xml" def articleNode = new NodeBuilder().article(id: '5') { title('Traversing XML in the nutshell') author { firstname('Martin') lastname('Schmidt') } 'release-date'('2019-05-18') } articles.article[0].replaceNode(articleNode) then: "Node is added to xml properly" articles.'*'.size() == 4 articles.article[0].title.text() == "Traversing XML in the nutshell" }

3.5. Deleting a Node

Deleting a node using the XmlParser is quite tricky. Although the Node class provides the remove(Node child) method, in most cases, we wouldn't use it by itself.

Instead, we'll show how to delete a node whose value fulfills a given condition.

By default, accessing the nested elements using a chain of Node.NodeList references returns a copy of the corresponding children nodes. Because of that, we can't use the java.util.NodeList#removeAll method directly on our article collection.

To delete a node by a predicate, we have to find all nodes matching our condition first, and then iterate through them and invoke java.util.Node#remove method on the parent each time .

Let's implement a test that removes all articles whose author has an id other than 3:

def "Should remove article from xml"() { given: "XML object" def articles = new XmlParser().parse(xmlFile) when: "Removing all articles but the ones with id==3" articles.article .findAll { it.author.'@id'.text() != "3" } .each { articles.remove(it) } then: "There is only one article left" articles.children().size() == 1 articles.article[0].author.'@id'.text() == "3" }

As we can see, as a result of our remove operation, we received an XML structure with only one article, and its id is 3.

4. XmlSlurper

Groovy also provides another class dedicated to working with XML. In this section, we'll show how to read and manipulate the XML structure using the XmlSlurper.

4.1. Reading

As in our previous examples, let's start with parsing the XML structure from a file:

def "Should read XML file properly"() { given: "XML file" when: "Using XmlSlurper to read file" def articles = new XmlSlurper().parse(xmlFile) then: "Xml is loaded properly" articles.'*'.size() == 4 articles.article[0].author.firstname == "Siena" articles.article[2].'release-date' == "2018-06-12" articles.article[3].title == "Java 12 insights" articles.article.find { it.author.'@id' == "3" }.author.firstname == "Daniele" }

As we can see, the interface is identical to that of XmlParser. However, the output structure uses the groovy.util.slurpersupport.GPathResult, which is a wrapper class for Node. GPathResult provides simplified definitions of methods such as: equals() and toString() by wrapping Node#text(). As a result, we can read fields and parameters directly using just their names.

4.2. Adding a Node

Adding a Node is also very similar to using XmlParser. In this case, however, groovy.util.slurpersupport.GPathResult#appendNode provides a method that takes an instance of java.lang.Object as an argument. As a result, we can simplify new Node definitions following the same convention introduced by NodeBuilder:

def "Should add node to existing xml"() { given: "XML object" def articles = new XmlSlurper().parse(xmlFile) when: "Adding node to xml" articles.appendNode { article(id: '5') { title('Traversing XML in the nutshell') author { firstname('Martin') lastname('Schmidt') } 'release-date'('2019-05-18') } } articles = new XmlSlurper().parseText(XmlUtil.serialize(articles)) then: "Node is added to xml properly" articles.'*'.size() == 5 articles.article[4].title == "Traversing XML in the nutshell" }

In case we need to modify the structure of our XML with XmlSlurper, we have to reinitialize our articles object to see the results. We can achieve that using the combination of the groovy.util.XmlSlurper#parseText and the groovy.xmlXmlUtil#serialize methods.

4.3. Modifying a Node

As we mentioned before, the GPathResult introduces a simplified approach to data manipulation. That being said, in contrast to the XmlSlurper, we can modify the values directly using the node name or parameter name:

def "Should modify node"() { given: "XML object" def articles = new XmlSlurper().parse(xmlFile) when: "Changing value of one of the nodes" articles.article.each { it.'release-date' = "2019-05-18" } then: "XML is updated" articles.article.findAll { it.'release-date' != "2019-05-18" }.isEmpty() }

Let's notice that when we only modify the values of the XML object, we don't have to parse the whole structure again.

4.4. Replacing a Node

Now let's move to replacing the whole node. Again, the GPathResult comes to the rescue. We can easily replace the node using groovy.util.slurpersupport.NodeChild#replaceNode, which extends GPathResult and follows the same convention of using the Object values as arguments:

def "Should replace node"() { given: "XML object" def articles = new XmlSlurper().parse(xmlFile) when: "Replacing node" articles.article[0].replaceNode { article(id: '5') { title('Traversing XML in the nutshell') author { firstname('Martin') lastname('Schmidt') } 'release-date'('2019-05-18') } } articles = new XmlSlurper().parseText(XmlUtil.serialize(articles)) then: "Node is replaced properly" articles.'*'.size() == 4 articles.article[0].title == "Traversing XML in the nutshell" }

As was the case when adding a node, we're modifying the structure of the XML, so we have to parse it again.

4.5. Deleting a Node

To remove a node using XmlSlurper, we can reuse the groovy.util.slurpersupport.NodeChild#replaceNode method simply by providing an empty Node definition:

def "Should remove article from xml"() { given: "XML object" def articles = new XmlSlurper().parse(xmlFile) when: "Removing all articles but the ones with id==3" articles.article .findAll { it.author.'@id' != "3" } .replaceNode {} articles = new XmlSlurper().parseText(XmlUtil.serialize(articles)) then: "There is only one article left" articles.children().size() == 1 articles.article[0].author.'@id' == "3" }

Again, modifying the XML structure requires reinitialization of our articles object.

5. XmlParser vs XmlSlurper

As we showed in our examples, the usages of XmlParser and XmlSlurper are pretty similar. We can more or less achieve the same results with both. However, some differences between them can tilt the scales towards one or the other.

First of all,XmlParser always parses the whole document into the DOM-ish structure. Because of that, we can simultaneously read from and write into it. We can't do the same with XmlSlurper as it evaluates paths more lazily. As a result, XmlParser can consume more memory.

On the other hand, XmlSlurper uses more straightforward definitions, making it simpler to work with. We also need to remember that any structural changes made to XML using XmlSlurper require reinitialization, which can have an unacceptable performance hit in case of making many changes one after another.

The decision of which tool to use should be made with care and depends entirely on the use case.

6. MarkupBuilder

Apart from reading and manipulating the XML tree, Groovy also provides tooling to create an XML document from scratch. Let's now create a document consisting of the first two articles from our first example using groovy.xml.MarkupBuilder:

def "Should create XML properly"() { given: "Node structures" when: "Using MarkupBuilderTest to create xml structure" def writer = new StringWriter() new MarkupBuilder(writer).articles { article { title('First steps in Java') author(id: '1') { firstname('Siena') lastname('Kerr') } 'release-date'('2018-12-01') } article { title('Dockerize your SpringBoot application') author(id: '2') { firstname('Jonas') lastname('Lugo') } 'release-date'('2018-12-01') } } then: "Xml is created properly" XmlUtil.serialize(writer.toString()) == XmlUtil.serialize(xmlFile.text) }

In the above example, we can see that MarkupBuilder uses the very same approach for the Node definitions we used with NodeBuilder and GPathResult previously.

To compare output from MarkupBuilder with the expected XML structure, we used the groovy.xml.XmlUtil#serialize method.

7. Conclusion

In this article, we explored multiple ways of manipulating XML structures using Groovy.

Kami melihat contoh parsing, menambah, mengedit, mengganti, dan menghapus node menggunakan dua kelas yang disediakan oleh Groovy: XmlParser dan XmlSlurper . Kami juga membahas perbedaan di antara mereka dan menunjukkan bagaimana kami dapat membuat pohon XML dari awal menggunakan MarkupBuilder .

Seperti biasa, kode lengkap yang digunakan dalam artikel ini tersedia di GitHub.