Untitled
unknown
java
a year ago
5.4 kB
14
Indexable
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
public class XMLModifier {
public static String xmlModify(String xmlContent, String xpathExpr, String operation, String value)
throws Exception {
// Parse the XML content
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlContent)));
// Create XPath expression
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
// Perform the operation
if ("delete".equalsIgnoreCase(operation)) {
deleteElement(doc, expr);
} else if ("update".equalsIgnoreCase(operation)) {
updateElement(doc, expr, value);
} else if ("create".equalsIgnoreCase(operation)) {
createElement(doc, xpathExpr, value);
} else {
throw new IllegalArgumentException("Invalid operation: " + operation);
}
// Convert Document to String
return convertDocumentToString(doc);
}
// Delete element(s) matching the XPath expression
private static void deleteElement(Document doc, XPathExpression expr) throws XPathExpressionException {
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
node.getParentNode().removeChild(node);
}
}
// Update element(s) matching the XPath expression with new value
private static void updateElement(Document doc, XPathExpression expr, String value) throws XPathExpressionException {
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (nodes.getLength() == 0) {
throw new IllegalArgumentException("No elements found for XPath: " + expr);
}
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
node.setTextContent(value);
}
}
// Create new element at the specified XPath location
private static void createElement(Document doc, String xpathExpr, String value) {
String[] parts = xpathExpr.split("/");
Node current = doc.getDocumentElement();
// Walk through the parts of the XPath and create elements as needed
for (String part : parts) {
if (part.isEmpty()) continue;
Node child = findChildNode(current, part);
if (child == null) {
// Create new node if it doesn't exist
Element newElement = doc.createElement(part);
current.appendChild(newElement);
current = newElement;
} else {
current = child;
}
}
// Set value of the final element
current.setTextContent(value);
}
// Helper method to find a child node with a specific tag name
private static Node findChildNode(Node parent, String tagName) {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(tagName)) {
return child;
}
}
return null;
}
// Convert the XML Document to a String
private static String convertDocumentToString(Document doc) throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
return writer.getBuffer().toString();
}
public static void main(String[] args) {
String xmlData = """
<root>
<item>
<name>Item 1</name>
<value>100</value>
</item>
<item>
<name>Item 2</name>
<value>200</value>
</item>
</root>
""";
String xpath = "/root/item[name='Item 2']/value";
String operation = "update"; // can be 'create', 'delete', 'update'
String value = "300";
try {
String modifiedXml = xmlModify(xmlData, xpath, operation, value);
System.out.println(modifiedXml);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Editor is loading...
Leave a Comment