前端之家收集整理的这篇文章主要介绍了
【深入JAVA】对xml节点添加属性,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在阅读的过程中有任何问题,欢迎一起交流
邮箱:1494713801@qq.com
QQ:1494713801
对xml中的节点<module name="test">添加属性节点为<module load="false" name="test">>
Java代码:
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
}
try {
inputDocument = builder.parse(new File(strFilename));
outputDocument = builder.newDocument();
} catch (SAXException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Node moduleNode = strModuleList.get(i); //找到要修改的节点moduleNode
if (moduleNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) moduleNode;
element.setAttribute("load","false");//设置属性load="false"
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former;
try {
former = factory.newTransformer();
former.transform(new DOMSource(inputDocument),new StreamResult("xml文件路径"));
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
((Element) moduleNode).setAttribute("load","false");
outputDocument.importNode(moduleNode,true);//写入xml文件
添加和删除属性
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class domTest3 {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("src/shuiguo.xml"));
createAttribute(doc);
removeAttribute(doc);
}
public static void removeAttribute(Document doc) throws Exception {
Node apple = doc.getElementsByTagName("苹果").item(0);
apple.getAttributes().removeNamedItem("id");
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former = factory.newTransformer();
former.transform(new DOMSource(doc),new StreamResult(new File(
"src/shuiguo.xml")));
}
public static void createAttribute(Document doc) throws Exception {
Node orange = doc.getElementsByTagName("桔子").item(0);
if (orange.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) orange;
element.setAttribute("id","333");
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former = factory.newTransformer();
former.transform(new DOMSource(doc),new StreamResult(new File(
"src/shuiguo.xml")));
}
}
}
参考链接:http://blog.csdn.net/sunkailu/article/details/8087305
原文链接:https://www.f2er.com/xml/296925.html