java修改xml文件中某个属性值
时间: 2023-10-08 14:05:13 浏览: 116
你可以使用Java的DOM解析器来修改XML文件中的某个属性值。具体步骤如下:
1. 加载XML文件并创建DOM文档对象。
```java
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("example.xml"));
```
2. 获取需要修改的元素节点。
```java
Element root = doc.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("book");
Element bookElement = null;
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
String id = element.getAttribute("id");
if (id.equals("001")) {
bookElement = element;
break;
}
}
```
3. 修改属性值。
```java
bookElement.setAttribute("price", "19.99");
```
4. 将修改后的DOM文档写入XML文件。
```java
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("example.xml"));
transformer.transform(source, result);
```
完整代码示例:
```java
import java.io.File;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class ModifyXML {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("example.xml"));
Element root = doc.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("book");
Element bookElement = null;
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
String id = element.getAttribute("id");
if (id.equals("001")) {
bookElement = element;
break;
}
}
bookElement.setAttribute("price", "19.99");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("example.xml"));
transformer.transform(source, result);
System.out.println("XML file updated successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文
相关推荐


















