Node.replaceChild
メソッドを使用してXHTML文字列から作成したDOMドキュメントのタグを<span>
タグに置き換えようとしています。どちらのタグも同じスタイル属性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());
}
}
この行にコメントが付いていると、スタイル属性は削除されます。この奇妙な行動を説明するには?ラインと
出力は次のようにコメント行と
<?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>