gpt4 book ai didi

java - 为什么 DOM Node.replaceChild() 方法在此用例中不起作用?

转载 作者:行者123 更新时间:2023-11-30 02:52:05 26 4
gpt4 key购买 nike

我正在尝试替换 <div>标记为 <span>使用 Node.replaceChild 从 XHTML 字符串创建的 DOM 文档中的标记方法。两个标签具有相同的样式属性 style="color: blue;" ,但是当我取消注释访问 style 属性内容的无用代码行时,我的代码就会按预期工作。这是我的测试代码:

public class DomTest {

public static void main(String args[]) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
+ " <head>\n"
+ " <title>Title</title>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div style=\"color: blue;\">Content</div>\n"
+ " </body>\n"
+ "</html>")));

Element element = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(
"<span style=\"color: blue;\">content</span>"))).getDocumentElement();

XPath xPath = XPathFactory.newInstance().newXPath();

Node parentNode = (Node) xPath.compile("/html[1]/body[1]")
.evaluate(doc, XPathConstants.NODE);

Node childNode = (Node) xPath.compile("/html[1]/body[1]/div[1]")
.evaluate(doc, XPathConstants.NODE);

// element.getAttributes().item(0).getNodeValue();

doc.adoptNode(element);
parentNode.replaceChild(element, childNode);

DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(domSource, result);

System.out.println(writer.toString());
}
}

当该行被注释时,样式属性将被删除。如何解释这种奇怪的行为?

带有注释行的输出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
</head>
<body>
<span style="">Content</span>
</body>
</html>

未注释行的输出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
</head>
<body>
<span style="color: blue">Content</span>
</body>
</html>

最佳答案

这是因为您使用了adoptNode()。您应该使用 importNode() 代替,例如

Node imported = doc.importNode(element, true);
parentNode.replaceChild(imported, childNode);

引用文献:

https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Document.html#adoptNode-org.w3c.dom.Node-

https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Document.html#importNode-org.w3c.dom.Node-boolean-

关于java - 为什么 DOM Node.replaceChild() 方法在此用例中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38317417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com