Really deleting nodes in XMLParser Object Groovy

前端 未结 2 1171
既然无缘
既然无缘 2021-02-06 17:34

How to REALLY remove a node via XMLParser:

 x=\'\'\'

 
   a
   b
 
 

        
相关标签:
2条回答
  • 2021-02-06 18:16

    Removing nodes works pretty much like other DOM APIs. You have to pass the node you want to delete to the remove method of its parent.

    Also the = operator is the assignment operator in Groovy. it.@C1 = 'a' would assign 'a' to the C1 attribute of each B node in the document. Since the result of that assignment is 'a', which is coerced to true by Groovy, find will always return the first node it encounters.

    xml=new XmlParser().parseText(x)
    def nodeToDel=xml.A.B.C1.find { it.text() == 'a' }
    def parent = nodeToDel.parent()
    parent.remove(nodeToDel)
    
    0 讨论(0)
  • 2021-02-06 18:34

    Improving solution of Justin Piper, with a fully working example:

    def xml = new XmlParser().parseText('''
        <root>
            <element id="10" />
            <element id="20" />
        </root>
    ''')
    def nodeToDel = xml.find { it["@id"] == '20' }
    
    if (nodeToDel) {
        nodeToDel.parent().remove(nodeToDel)
    }
    
    println xml
    
    0 讨论(0)
提交回复
热议问题