Groovy nodebuilder как добавить атрибут в узел
Перейти к содержимому

Groovy nodebuilder как добавить атрибут в узел

  • автор:

Groovy nodebuilder как добавить атрибут в узел

Growth supply ticket где использовать Reddit and its partners use cookies and similar technologies to provide you with a better experience. By accepting all cookies,… Подробнее » Growth supply ticket где использовать

Gross beat как замедлить в 2 раза

  • автор: admin
  • 02.10.2023

IL Gross Beat Настройки времени Эти элементы управления относятся к назначаемым огибающим времени/высоты тона: time (время) — настройка подмешивания назначаемой временной огибающей. Диапазон: от 0%… Подробнее » Gross beat как замедлить в 2 раза

Groovy nodebuilder как добавить атрибут в узел

  • автор: admin
  • 02.10.2023

Working with XML in Groovy Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in… Подробнее » Groovy nodebuilder как добавить атрибут в узел

Green satoshi token что это

  • автор: admin
  • 02.10.2023

What is STEPN (GMT) crypto? The cryptocurrency world keeps growing and metamorphosing. New digital assets get released regularly, and new trends start dominating the market… Подробнее » Green satoshi token что это

Grayscale bitcoin trust что это

  • автор: admin
  • 02.10.2023

Что такое Grayscale: как работает один из главных инвесторов в криптовалюты Недавно инвестиционный фонд Grayscale был мостом между традиционным и крипторынком для квалифицированных трейдеров. Однако… Подробнее » Grayscale bitcoin trust что это

Groovy nodebuilder как добавить атрибут в узел

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses — Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

30% less RAM and a 30% smaller base image for running a Spring Boot application? Yes, please.

Alpaquita Linux was designed to efficiently run containerized Java applications.

It’s meant to handle heavy workloads and do it well.

And the Alpaquita Containers incorporates Liberica JDK Lite, a Java runtime tailored to cloud-based services:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Introduction

Groovy provides a substantial number of methods dedicated to traversing and manipulating XML content.

In this tutorial, we’ll demonstrate how to add, edit, or delete elements from XML in Groovy using various approaches. We’ll also show how to create an XML structure from scratch.

2. Defining the Model

Let’s define an XML structure in our resources directory that we’ll use throughout our examples:

And read it into an InputStream variable:

3. XmlParser

Let’s start exploring this stream with the XmlParser class.

3.1. Reading

Reading and parsing an XML file is probably the most common XML operation a developer will have to do. The XmlParser provides a very straightforward interface meant for exactly that:

At this point, we can access the attributes and values of XML structure using GPath expressions.

Let’s now implement a simple test using Spock to check whether our articles object is correct:

To understand how to access XML values and how to use the GPath expressions, let’s focus for a moment on the internal structure of the result of the XmlParser#parse operation.

The articles object is an instance of groovy.util.Node. Every Node consists of a name, attributes map, value, and parent (which can be either null or another Node).

In our case, the value of articles is a groovy.util.NodeList instance, which is a wrapper class for a collection of Nodes. The NodeList extends the java.util.ArrayList class, which provides extraction of elements by index. To obtain a string value of a Node, we use groovy.util.Node#text().

In the above example, we introduced a few GPath expressions:

  • articles.article[0].author.firstname — get the author’s first name for the first article – articles.article[n] would directly access the nth article
  • ‘*’ — get a list of article‘s children – it’s the equivalent of groovy.util.Node#children()
  • author.’@id’ — get the author element’s id attribute – author.’@attributeName’ accesses the attribute value by its name (the equivalents are: author[‘@id’] and author.@id)
3.2. Adding a Node

Similar to the previous example, let’s read the XML content into a variable first. This will allow us to define a new node and add it to our articles list using groovy.util.Node#append.

Let’s now implement a test which proves our point:

As we can see in the above example, the process is pretty straightforward.

Let’s also notice that we used groovy.util.NodeBuilder, which is a neat alternative to using the Node constructor for our Node definition.

3.3. Modifying a Node

We can also modify the values of nodes using the XmlParser. To do so, let’s once again parse the content of the XML file. Next, we can edit the content node by changing the value field of the Node object.

Let’s remember that while XmlParser uses the GPath expressions, we always retrieve the instance of the NodeList, so to modify the first (and only) element, we have to access it using its index.

Let’s check our assumptions by writing a quick test:

In the above example, we’ve also used the Groovy Collections API to traverse the NodeList.

3.4. Replacing a Node

Next, let’s see how to replace the whole node instead of just modifying one of its values.

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:

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:

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:

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:

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:

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:

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:

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:

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.

We looked at examples of parsing, adding, editing, replacing, and deleting nodes using two classes provided by Groovy: XmlParser and XmlSlurper. We also discussed differences between them and showed how we could build an XML tree from scratch using MarkupBuilder.

As always, the complete code used in this article is available over on GitHub.

Работа с XML в Groovy

Groovy предоставляет значительное количество методов, предназначенных для просмотра и управления содержимым XML.

В этом руководстве мы продемонстрируем, как добавлять, редактировать или удалять элементы из XML в Groovy с использованием различных подходов. Мы также покажем, как создать структуру XML с нуля .

2. Определение модели

Давайте определим структуру XML в нашем каталоге ресурсов, которую мы будем использовать в наших примерах:

И прочтите его в переменной InputStream :

3. XmlParser

Начнем изучать этот поток с класса XmlParser .

3.1. Чтение

Чтение и синтаксический анализ файла XML, вероятно, является наиболее распространенной операцией XML, которую должен выполнить разработчик. XmlParser обеспечивает очень простой интерфейс означало именно для этой цели :

На этом этапе мы можем получить доступ к атрибутам и значениям структуры XML с помощью выражений GPath.

Давайте теперь реализуем простой тест с помощью Spock, чтобы проверить, верен ли наш объект статей :

Чтобы понять, как получить доступ к значениям XML и как использовать выражения GPath, давайте сосредоточимся на внутренней структуре результата операции синтаксического анализа XmlParser # .

Объект статей — это экземпляр groovy.util.Node. Каждый узел состоит из имени, карты атрибутов, значения и родителя (который может быть либо нулевым, либо другим узлом) .

В нашем случае стоимость изделий является groovy.util.NodeList экземпляр, который является классом — оболочки для коллекции Node s. NodeList расширяет java.util.ArrayList класс, который обеспечивает извлечение элементов по индексу. Чтобы получить строковое значение узла, мы используем groovy.util.Node # text ().

В приведенном выше примере мы ввели несколько выражений GPath:

  • article.article [0] .author.firstname — получить имя автора для первой статьи — article.article[n] будет иметь прямой доступ к n- й статье
  • ‘*’ — получить список дочерних элементов статьи — это эквивалент groovy.util.Node # children ()
  • author.’@id ‘ — получить атрибут id элемента автораauthor.’@attributeName’ получает доступ к значению атрибута по его имени (эквиваленты: author [‘@ id’] и [email protected] )
3.2. Добавление узла

Как и в предыдущем примере, давайте сначала прочитаем содержимое XML в переменную. Это позволит нам определить новый узел и добавить его в список статей с помощью groovy.util.Node # append.

Теперь давайте проведем тест, подтверждающий нашу точку зрения:

Как видно из приведенного выше примера, процесс довольно прост.

Также обратите внимание, что мы использовали groovy.util.NodeBuilder, который является прекрасной альтернативой использованию конструктора узла для нашего определения узла .

3.3. Изменение узла

Мы также можем изменить значения узлов с помощью XmlParser . Для этого давайте еще раз проанализируем содержимое XML-файла. Затем мы можем отредактировать узел содержимого, изменив поле значения объекта узла .

Давайте вспомним, что хотя XmlParser использует выражения GPath, мы всегда извлекаем экземпляр NodeList, поэтому для изменения первого (и единственного) элемента мы должны получить к нему доступ, используя его индекс.

Давайте проверим наши предположения, написав небольшой тест:

В приведенном выше примере мы также использовали Groovy Collections API для обхода NodeList .

3.4. Замена узла

Затем давайте посмотрим, как заменить весь узел, а не просто изменить одно из его значений.

Подобно добавлению нового элемента, мы будем использовать NodeBuilder для определения узла, а затем заменим один из существующих узлов внутри него, используя groovy.util.Node # replaceNode :

3.5. Удаление узла

Удалить узел с помощью XmlParser довольно сложно. Хотя класс Node предоставляет метод remove (дочерний узел) , в большинстве случаев мы бы не использовали его отдельно.

Вместо этого мы покажем, как удалить узел, значение которого удовлетворяет заданному условию.

По умолчанию доступ к вложенным элементам с использованием цепочки ссылок Node.NodeList возвращает копию соответствующих дочерних узлов. Из-за этого мы не можем использовать метод java.util.NodeList # removeAll непосредственно в нашей коллекции статей .

Чтобы удалить узел по предикату, мы должны сначала найти все узлы, соответствующие нашему условию, а затем перебрать их и каждый раз вызывать метод java.util.Node # remove для родительского элемента.

Давайте реализуем тест, который удаляет все статьи, у автора которых идентификатор отличный от 3 :

Как мы видим, в результате нашей операции удаления мы получили XML-структуру только с одной статьей, и ее идентификатор равен 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:

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:

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:

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:

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:

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:

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.

Мы рассмотрели примеры синтаксического анализа, добавления, редактирования, замены и удаления узлов с использованием двух классов, предоставляемых Groovy: XmlParser и XmlSlurper . Мы также обсудили различия между ними и показали, как с помощью MarkupBuilder построить XML-дерево с нуля .

Как всегда, полный код, использованный в этой статье, доступен на GitHub.

Adding dynamic elements and attributes to groovy MarkupBuilder or StreamingMarkupBuilder [closed]

I’ve seen many example using Groovy’s MarkupBuilder for building an XML document, but they all seem to use static attributes for every element in the document (the attribute names are all known at compile time). What if I’m trying to construct an XML document where the attribute names aren’t known until runtime? I haven’t yet figured out the syntax require to solve a problem like this.

[Java] Узел класса

Представляет произвольный узел дерева, который может использоваться для структурированных метаданных или любого произвольного XML-подобного дерева. Узел может иметь имя, значение и дополнительную карту атрибутов. Обычно имя представляет собой строку, а значение представляет собой строку или список других узлов, хотя типы могут быть расширяемыми для обеспечения гибкой структуры, например, вы можете использовать QName в качестве имени, которое включает URI пространства имен и локальное имя. Или имя объекта JMX и т. Д. Таким образом, этот класс может представлять метаданные, такие как , или вложенные метаданные, например >

Constructor Summary

Constructors

Methods Summary

Краткое описание унаследованных методов

Inherited Methods

Constructor Detail

общедоступный узел ( родительский узел , имя объекта )

Создает новый узел с именем name и, если указан родительский узел, добавляет вновь созданный узел как дочерний по отношению к родительскому.

Parameters: parent — родительский узел или ноль, если нет родителя name — имя узла

общественный узел ( узел родитель, объект имя, объект значение)

Создает новый узел с именем name со значением value и, если указан родительский узел, добавляет вновь созданный узел как дочерний по отношению к родительскому.

Parameters: parent — родительский узел или ноль, если нет родителя name — имя узла value — значение узла, например некоторый текст, но в целом любой объект

общедоступный узел ( родительский узел , имя объекта , атрибуты карты )

Создает новый узел с именем name с атрибутами, указанными в attributes Map. Если указан родительский элемент, вновь созданный узел добавляется как дочерний по отношению к родительскому элементу.

Parameters: parent — родительский узел или ноль, если нет родителя name — имя узла attributes — Карта пар имя-значение

общедоступный узел ( родительский узел , имя объекта , атрибуты карты , значение объекта )

Создает новый узел с именем name со значением value и атрибутами, указанными в attributes Map. Если указан родительский элемент, вновь созданный узел добавляется как дочерний по отношению к родительскому элементу.

Parameters: parent — родительский узел или ноль, если нет родителя name — имя узла attributes — Карта пар имя-значение value — значение узла, например некоторый текст, но в целом любой объект

Method Detail

публичное логическое добавление ( дочерний узел )

Добавляет дочерний узел к текущему узлу.

Parameters: child — ребенок, чтобы добавить Returns: true

общедоступный узел appendNode ( имя объекта , атрибуты карты )

Создает новый узел в качестве дочернего узла текущего узла.

Parameters: name — имя нового узла attributes — атрибуты нового узла Returns: вновь созданный Node

общедоступный узел appendNode ( имя объекта )

Создает новый узел в качестве дочернего узла текущего узла.

Parameters: name — имя нового узла Returns: вновь созданный Node

общественный узел appendNode ( Объект имя, объект значение)

Создает новый узел в качестве дочернего узла текущего узла.

Parameters: name — имя нового узла value — значение нового узла Returns: вновь созданный Node

общедоступный узел appendNode ( имя объекта , атрибуты карты , значение объекта )

Создает новый узел в качестве дочернего узла текущего узла.

Parameters: name — имя нового узла attributes — атрибуты нового узла value — значение нового узла Returns: вновь созданный Node

публичный объект атрибут ( Object ключ)

Обеспечивает поиск атрибутов по ключу.

Parameters: key — ключ интереса Returns: атрибут, соответствующий ключу, или null если совпадения не существует

public Mapattributes()

Возвращает Map атрибутов узла или пустую Map если узел не имеет атрибутов.

Returns: атрибуты узла

public ListbreadthFirst()

Предоставляет коллекцию всех узлов в дереве,используя обход в первом порядке.

Returns: список (в порядке убывания)упорядоченных узлов

public List widththFirst (логический предварительный порядок)

Предоставляет коллекцию всех узлов в дереве,используя обход по ширине.

Parameters: preorder — если false, будет выполняться постзаказный обход в ширину Returns: список (в порядке убывания)упорядоченных узлов Since: 2.5.0

Похожие публикации:

  1. Как закрыть карту халва от совкомбанка
  2. Как россия будет закупать процессоры
  3. Какой процент по кредитке тинькофф
  4. Что такое деген в крипте

Groovy nodebuilder как добавить атрибут в узел

Package: groovy.util

[Java] Class NodeBuilder

  • groovy.util.NodeBuilder

Methods Summary

Methods

Type Params Return Type Name and description
protected Object createNode(Object name)
protected Object createNode(Object name, Object value)
protected Object createNode(Object name, Map attributes)
protected Object createNode(Object name, Map attributes, Object value)
protected Node getCurrentNode()
public static NodeBuilder newInstance()
protected void setParent(Object parent, Object child)

Inherited Methods Summary

Inherited Methods

Methods inherited from class Name
class BuilderSupport createNode, createNode, createNode, createNode, doInvokeMethod, getCurrent, getName, invokeMethod, invokeMethod, nodeCompleted, postNodeCompletion, setClosureDelegate, setCurrent, setParent
class GroovyObjectSupport getMetaClass, setMetaClass

Method Detail

@Override
protected Object createNode(Object name)
@Override
protected Object createNode(Object name, Object value)
@Override
protected Object createNode(Object name, Map attributes)
@Override
protected Object createNode(Object name, Map attributes, Object value)
protected Node getCurrentNode()
public static NodeBuilder newInstance()
@Override
protected void setParent(Object parent, Object child)
  • Summary: Nested Field Constructor
  • Method
  • | Detail: Field Constructor
  • Method

Copyright © 2003-2024 The Apache Software Foundation. All rights reserved.

How to add XML attribute using Groovy?

I need to add @ attribute to the root element of XML fragment in Groovy. I want to use XmlSlurper . How to do it? Adding elements is easy.

asked Oct 17, 2011 at 14:47
7,592 4 4 gold badges 42 42 silver badges 50 50 bronze badges

2 Answers 2

Run this in the Groovy console to verify that it works

import groovy.xml.StreamingMarkupBuilder // the original XML def input = " " // add attributeName="attributeValue" to the root def root = new XmlSlurper().parseText(input) root.@attributeName = 'attributeValue' // get the modified XML and check that it worked def outputBuilder = new StreamingMarkupBuilder() String updatedXml = outputBuilder.bind < mkp.yield root >assert " " == updatedXml 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *