java将xml字符串转为xml并更改节点内容
时间: 2023-07-29 15:10:42 浏览: 108
可以使用Java中的DOM(Document Object Model)库来实现将XML字符串转换为XML文档,并且可以更改节点内容。下面是一个示例代码:
```java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class XMLUtils {
public static void main(String[] args) {
String xmlString = "<root><node1>value1</node1><node2>value2</node2></root>";
String nodeName = "node1";
String nodeValue = "new value";
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xmlString));
Document doc = builder.parse(inputSource);
// Find the node with the given name
NodeList nodeList = doc.getElementsByTagName(nodeName);
Node node = nodeList.item(0);
// Update the node value
node.setTextContent(nodeValue);
// Convert the updated document to a string
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (ParserConfigurationException | SAXException | IOException | TransformerException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们首先定义了一个XML字符串和要更改的节点名称及节点值。然后,我们使用DocumentBuilderFactory和DocumentBuilder对象将XML字符串转换为XML文档。接下来,我们使用getElementsByTagName方法查找要更改的节点,并使用setTextContent方法更改节点的值。最后,我们使用TransformerFactory和Transformer对象将更新后的XML文档转换回字符串,并将其打印到控制台上。
阅读全文