2009-03-05 6 views
2

XHTMLドキュメントのすべてのエンティティリファレンスを解決し、IEが理解できるプレーンなXHTMLドキュメントに変換するにはどうすればよいですか? 例XHTML: - "EntityHandling"XMLですべてのエンティティリファレンスを解決し、C#で新しいXMLを作成するにはどうすればよいですか?

<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE html [ 
    <!ENTITY D "&#x2014;"> 
    <!ENTITY o "&#x2018;"> 
    <!ENTITY c "&#x2019;"> 
    <!ENTITY O "&#x201C;"> 
    <!ENTITY C "&#x201D;"> 
]> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    </head> 
    <body> 
     &O; &C; 
    </body> 
</html> 
+0

MSIEは完全に法的なXHTMLを表示できません。このくそは本当に壊れています。 – bortzmeyer

答えて

2

が、これは簡単なのXmlTextReaderでのオプション(およびXmlValidatingReaderを)クラスで判明します。

だからあなたの問題の簡単なデモ:

System.Xml.XmlTextReader textReader = new System.Xml.XmlTextReader("testin.xml"); 
textReader.EntityHandling = System.Xml.EntityHandling.ExpandEntities; 
System.Xml.XmlDocument outputDoc = new System.Xml.XmlDocument(); 
outputDoc.Load(textReader); 
System.Xml.XmlDocumentType docTypeIfPresent = outputDoc.DocumentType; 
if (docTypeIfPresent != null) 
    outputDoc.RemoveChild(docTypeIfPresent); 
outputDoc.Save("testout.html"); 
textReader.Close(); 

そして、あなたは、メモリにストリーミング同等の文書をロードする必要がしたくない場合:

System.Xml.XmlTextReader textReader = new System.Xml.XmlTextReader("testin.xml"); 
textReader.EntityHandling = System.Xml.EntityHandling.ExpandEntities; 
System.Xml.XmlTextWriter textWriter = new System.Xml.XmlTextWriter("testout.html", System.Text.Encoding.UTF8); 
while (textReader.Read()) 
{ 
    if (textReader.NodeType != System.Xml.XmlNodeType.DocumentType) 
     textWriter.WriteNode(textReader, false); 
    else 
     textReader.Skip(); 
} 
textWriter.Close(); 
+0

XmlWriterSettings writerSettings =新しいXmlWriterSettings(); writerSettings.OmitXmlDeclaration = true; XmlWriter xmlWriter = XmlWriter.Create(htmlFileName、writerSettings); outputDoc.Save(xmlWriter); xmlWriter.Close(); –

+0

こんにちは、私はコメントを理解していない - OmitXmlDeclarationもDTDを省略しますか?実際にXML宣言を削除するという望ましくない副作用はないでしょうか? (これはエンコードの問題を引き起こす可能性があります) – Tao

+0

outputDoc.Save( "testout.html"); 私のコードでは、xml宣言が省略され、XMLの代わりにプレーンhtmlが生成される –

0

xmllintはそれを行うことができますと、 xmllintはC言語で記述されており、フリーソフトウェアであるため、C#プログラムでの使用方法を比較的容易に変更することができます。ここに例があります:

% cat foo.xhtml 
<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE html [ 
    <!ENTITY D "&#x2014;"> 
    <!ENTITY o "&#x2018;"> 
    <!ENTITY c "&#x2019;"> 
    <!ENTITY O "&#x201C;"> 
    <!ENTITY C "&#x201D;"> 
]> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    </head> 
    <body> 
     &O; &C; 
    </body> 
</html> 

% xmllint --noent --dropdtd foo.xhtml 
<?xml version="1.0" encoding="utf-8"?> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    </head> 
    <body> 
     [Plain Unicode characters that I prefer to omit because I don't know how SO handles it] 
    </body> 
</html> 
関連する問題