0
我試圖用<span>
標記替換<div>
標記,該標記使用Node.replaceChild
方法從XHTML字符串創建的DOM文檔中。這兩個標籤都具有相同的樣式屬性style="color: blue;"
,但是當我取消訪問樣式屬性內容的無用代碼行時,我的代碼正常工作。這是我的測試代碼:爲什麼DOM Node.replaceChild()方法在這個用例中不起作用?
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());
}
}
當該行被註釋時,style屬性被刪除。如何解釋這種奇怪的行爲?
輸出與行註釋:
<?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>