Bekerja dengan XML di Groovy

1. Pengenalan

Groovy menyediakan sebilangan besar kaedah yang dikhaskan untuk melintasi dan memanipulasi kandungan XML.

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

2. Mendefinisikan Model

Mari tentukan struktur XML di direktori sumber kami yang akan kami gunakan sepanjang contoh kami:

  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 pemboleh ubah InputStream :

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

3. XmlParser

Mari mulakan penerokaan aliran ini dengan kelas XmlParser .

3.1. Membaca

Membaca dan mengurai fail XML mungkin merupakan operasi XML yang paling biasa yang perlu dilakukan oleh pembangun. The XmlParser menyediakan antara muka yang sangat mudah bertujuan untuk betul-betul bahawa:

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

Pada ketika ini, kita dapat mengakses atribut dan nilai struktur XML menggunakan ungkapan GPath.

Sekarang mari kita laksanakan ujian mudah menggunakan Spock untuk memeriksa sama ada objek artikel kita betul:

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 bagaimana menggunakan ungkapan GPath, mari kita fokus sejenak pada struktur dalaman hasil operasi # parser XmlParser .

The artikel objek adalah contoh groovy.util.Node. Setiap Node terdiri daripada nama, peta atribut, nilai, dan induk (yang boleh menjadi Null atau Node lain ) .

Dalam kes kami, nilai artikel adalah contoh groovy.util.NodeList , yang merupakan kelas pembungkus untuk koleksi Node s. The NodeList memanjangkan java.util.ArrayList kelas, yang menyediakan pengekstrakan unsur-unsur dengan indeks. Untuk mendapatkan nilai rentetan Node, kami menggunakan teks groovy.util.Node # ().

Dalam contoh di atas, kami memperkenalkan beberapa ungkapan GPath:

  • articles.article [0] .author.firstname - dapatkan nama pertama pengarang untuk artikel pertama - articles.article [n] secara langsung akan mengakses n artikel th
  • '*' - dapatkan senarai anak-anak artikel - ia setara dengan groovy.util . Node # kanak-kanak ()
  • author.'@id ' - dapatkan atribut id elemen pengarang - author.'@attributeName' mengakses nilai atribut dengan namanya (yang setara adalah: author ['@ id'] dan [dilindungi e-mel] )

3.2. Menambah Node

Sama seperti contoh sebelumnya, mari kita baca kandungan XML menjadi pemboleh ubah terlebih dahulu. Ini akan membolehkan kita menentukan simpul baru dan menambahkannya ke senarai artikel kita menggunakan groovy.util.Node # append.

Sekarang mari kita laksanakan ujian 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 dapat kita lihat dalam contoh di atas, prosesnya cukup mudah.

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

3.3. Mengubah Node

Kita juga boleh mengubah nilai nod menggunakan XmlParser . Untuk melakukannya, mari sekali lagi menghuraikan kandungan fail XML. Seterusnya, kita dapat mengedit simpul kandungan dengan mengubah bidang nilai objek Node .

Mari kita ingat bahawa semasa XmlParser menggunakan ungkapan GPath, kita selalu mendapatkan contoh NodeList, jadi untuk mengubah elemen pertama (dan satu-satunya), kita harus mengaksesnya menggunakan indeksnya.

Mari periksa andaian kami dengan menulis ujian pantas:

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 API Koleksi Groovy untuk melintasi NodeList .

3.4. Mengganti Node

Seterusnya, mari kita lihat cara mengganti keseluruhan nod dan bukannya hanya mengubah salah satu nilainya.

Begitu juga dengan menambahkan elemen baru, kita akan menggunakan NodeBuilder untuk definisi Node dan kemudian mengganti salah satu nod yang ada di dalamnya menggunakan groovy.util.Node # ReplNode :

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. Memadamkan Node

Memadamkan nod menggunakan XmlParser agak sukar. Walaupun kelas Node menyediakan kaedah hapus (anak Node) , dalam kebanyakan kes, kami tidak akan menggunakannya dengan sendirinya.

Sebagai gantinya, kami akan menunjukkan cara menghapus nod yang nilainya memenuhi syarat tertentu.

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 penghuraian, penambahan, penyuntingan, penggantian, dan penghapusan nod menggunakan dua kelas yang disediakan oleh Groovy: XmlParser dan XmlSlurper . Kami juga membincangkan perbezaan di antara mereka dan menunjukkan bagaimana kita dapat membina pokok XML dari awal menggunakan MarkupBuilder .

Seperti biasa, kod lengkap yang digunakan dalam artikel ini terdapat di GitHub.