Web標準はHTML5ですが、プログラムから扱う場合XMLモジュール(System.Xml.XmlDocumentクラスなど)が使えるXHTMLの方が便利だったりします。
HTML5のもつ最新機能は使えませんが、互換性は概ね問題なさそうなのでPowerShellでXHTMLを新規作成するコードを試してみたいと思います。
ソースコード
# 出力ファイルパスを指定します
$filePath = ".\sample-xhtml.html"
# XmlDocumentオブジェクトを作成します
$xmlDoc = New-Object System.Xml.XmlDocument
# XML宣言とXHTMLのDOCTYPEを定義します
# DOCTYPEはXmlDocumentでは直接ノードとして追加できないため、XmlDeclarationと組み合わせる方法で処理します
# XHTML 1.0 Transitional の DOCTYPE
$doctypePublicId = "-//W3C//DTD XHTML 1.0 Transitional//EN"
$doctypeSystemId = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
$doctypeNode = $xmlDoc.CreateDocumentType("html", $doctypePublicId, $doctypeSystemId, $null)
# XML宣言を作成します
$xmlDeclaration = $xmlDoc.CreateXmlDeclaration("1.0", "utf-8", $null)
$xmlDoc.AppendChild($xmlDeclaration) | Out-Null
# DOCTYPEノードをXML宣言の後に挿入します
$xmlDoc.InsertAfter($doctypeNode, $xmlDeclaration) | Out-Null
# ルート要素 (<html>) を作成し、XML名前空間と属性を設定します
$htmlElement = $xmlDoc.CreateElement("html")
# XHTMLの名前空間を設定
$htmlElement.SetAttribute("xmlns", "http://www.w3.org/1999/xhtml")
$htmlElement.SetAttribute("lang", "ja")
$htmlElement.SetAttribute("xml:lang", "ja") # XHTMLに必要な属性
$xmlDoc.AppendChild($htmlElement) | Out-Null
# head要素を作成し、<html>の子として追加します
$headElement = $xmlDoc.CreateElement("head")
$htmlElement.AppendChild($headElement) | Out-Null
# title要素を作成し、<head>の子として追加します
$titleElement = $xmlDoc.CreateElement("title")
$titleElement.InnerText = "PowerShellで作成したXHTMLファイル"
$headElement.AppendChild($titleElement) | Out-Null
# meta要素 (charset) を作成し、<head>の子として追加します (XHTMLでは空要素も閉じる必要があります)
$metaElement = $xmlDoc.CreateElement("meta")
$metaElement.SetAttribute("http-equiv", "Content-Type")
$metaElement.SetAttribute("content", "text/html; charset=utf-8")
$headElement.AppendChild($metaElement) | Out-Null
# body要素を作成し、<html>の子として追加します
$bodyElement = $xmlDoc.CreateElement("body")
$htmlElement.AppendChild($bodyElement) | Out-Null
# p要素を作成し、<body>の子として追加します
$pElement = $xmlDoc.CreateElement("p")
$pElement.SetAttribute("id", "Msg1")
$pElement.InnerText = "これはPowerShellのSystem.Xml.XmlDocumentで作成されたXHTMLのサンプルです。"
$bodyElement.AppendChild($pElement) | Out-Null
# ファイルを保存します
$xmlDoc.Save($filePath)
Write-Host "XHTMLファイルが以下のパスに作成されました: $filePath"
作成されたXHTML
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"[]>
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<head>
<title>PowerShellで作成したXHTMLファイル</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p id="Msg1">これはPowerShellのSystem.Xml.XmlDocumentで作成されたXHTMLのサンプルです。</p>
</body>
</html>
コメント