updating a property of a xml tag

后端 未结 1 1172
日久生厌
日久生厌 2021-01-28 04:19

Given a xml file as input howto modify a attribute of a tag with a new string value?

Function is

updateXMLAttribute(Document doc , String tag, String at         


        
相关标签:
1条回答
  • 2021-01-28 04:44

    I assume, by Document you mean org.w3c.dom.Document:

    updateXMLAttribute(Document doc , String tag, String attribute, String newValue) {
       NodeList nodes = doc.getElementsByTagName(tag);
       for(int i=0; i<nodes.getLength(); i++) {
           if(nodes.item(i) instanceof Element) {
               Element elem = (Element)nodes.item(i);
               Attr attribute = elem.getAttributeNode(attribute);
               attribute.setValue(newValue);
           }
       }
    }
    

    This will update all attribute values of attributes named in elements named in a dom document. Of course, you should add appropriate error handling and null-checks.

    PS: You can find all the information in the dom api documentation: http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/Document.html

    0 讨论(0)
提交回复
热议问题