【发布时间】:2011-09-16 22:46:14
【问题描述】:
给定一个 xml 文件作为输入,如何用新的字符串值修改标签的属性?
功能是
updateXMLAttribute(Document doc , String tag, String attribute, String newValue){
//impl
}
我该怎么做?
【问题讨论】:
给定一个 xml 文件作为输入,如何用新的字符串值修改标签的属性?
功能是
updateXMLAttribute(Document doc , String tag, String attribute, String newValue){
//impl
}
我该怎么做?
【问题讨论】:
我假设,您所说的 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
【讨论】: