<dependencies> <dependency> <groupId>org.webjars.npm</groupId> <artifactId>d3</artifactId> <version>5.15.1</version> </dependency> </dependencies> import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import java.io.StringReader; public class D3SelectionExample { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String xml = "<html><body><div id='myDiv'>Hello, D3 Selection!</div></body></html>"; InputSource inputSource = new InputSource(new StringReader(xml)); Document document = builder.parse(inputSource); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); String expression = "//div[@id='myDiv']"; NodeList nodeList = (NodeList) xPath.evaluate(expression, document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; element.setTextContent("Hello, D3 Selection Updated!"); } } String updatedXml = toString(document); System.out.println(updatedXml); } private static String toString(Document document) throws Exception { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); return writer.getBuffer().toString(); } }


上一篇:
下一篇:
切换中文