XMLですべてのエンティティ参照を解決し、C#で新しいXMLを作成する方法

StackOverflow https://stackoverflow.com/questions/614067

  •  03-07-2019
  •  | 
  •  

質問

XHTMLドキュメント内のすべてのエンティティ参照を解決し、IEが理解できるプレーンなXHTMLドキュメントに変換するにはどうすればよいですか? 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>
役に立ちましたか?

解決

これは、XmlTextReader(およびXmlValidatingReader)クラスの単純なオプションである&quot; EntityHandling&quot;を有効にします。

問題の簡単なデモ:

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();

他のヒント

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>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top