我使用groovy使用XmlParser解析XML文件。为了避免处理名称空间前缀,我使用了xmlRoot。'**'。findAll()方法来查找一些节点。该示例代码显示了如何正确工作,直到我刚刚读取节点,因为传递给闭包的每个项目都是一个Node对象。但是,当我更改节点的内容(在这种情况下,仅是节点的文本)时,对findAll的下一次调用不会在Node对象上进行迭代。对于我在文本中输入的每个字符,将String对象传递给闭包。我用instanceof检查类型来解决它,但这似乎是一个错误。
我做错了什么还是一个错误?
class XmlParserTest {
static final String XML_SAMPLE = """
<ns0:root xmlns:ns0="mycompany.com">
<ns0:firstParent>
<ns0:item1>uppercase_me!</ns0:item1>
</ns0:firstParent>
<ns0:secondParent>
<ns0:item2>uppercase_me_too!/ns0:item2>
</ns0:secondParent>
</ns0:root>
"""
static void main(String[] args) {
def xmlRoot = new XmlParser(false, false).parseText(XML_SAMPLE)
//******* find item1 and capitalize its text ********
def nds1 = xmlRoot.'**'.findAll {
it.name().equals("ns0:item1")
}
Node nd1 = nds1[0]
//This changes the text of the node, but something strange happens to the node tree
nd1.setValue(nd1.value().toString().toUpperCase())
//The same problem happens using replaceNode() instead of setValue()
//Node newNode = new Node(nd1.parent(), nd1.name(), nd1.value().toString().toUpperCase())
//nd1.replaceNode(newNode)
//******* find item2 and capitalize its text ********
def nds2 = xmlRoot.'**'.findAll {
//for each character in the string "uppercase me!" a String is passed instead of Node
//As String doesn't have a name method, an exception is raised
it.name().equals("ns0:item2")
//using instanceof fixes the problem, at least for this case
it instanceof Node && it.name().equals("ns0:item2")
}
Node nd2 = nds2[0]
nd2.setValue(nd2.value().toString().toUpperCase())
assert nd1.value().toString() == nd1.value().toString().toUpperCase()
assert nd2.value().toString() == nd2.value().toString().toUpperCase()
}
}