【问题标题】:updating a property of a xml tag更新 xml 标记的属性
【发布时间】:2011-09-16 22:46:14
【问题描述】:

给定一个 xml 文件作为输入,如何用新的字符串值修改标签的属性?

功能是

updateXMLAttribute(Document doc , String tag, String attribute, String newValue){

//impl

}

我该怎么做?

【问题讨论】:

    标签: java xml


    【解决方案1】:

    我假设,您所说的 Document 是指 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);
           }
       }
    }
    

    这将更新在 dom 文档中命名的元素中命名的属性的所有属性值。 当然,您应该添加适当的错误处理和空检查。

    PS:你可以在dom api文档中找到所有信息:http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/Document.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多