Come risolvere tutti i riferimenti alle entità in XML e creare un nuovo XML in C #?
Domanda
Come posso risolvere tutti i riferimenti alle entità nel documento XHTML e convertirlo in un semplice documento XHTML che IE può capire? L'esempio XHTML:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html [
<!ENTITY D "—">
<!ENTITY o "‘">
<!ENTITY c "’">
<!ENTITY O "“">
<!ENTITY C "”">
]>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
&O; &C;
</body>
</html>
Soluzione
Si scopre che questa è una semplice opzione nella classe XmlTextReader (e XmlValidatingReader) - " EntityHandling " ;.
Quindi una semplice demo del tuo problema:
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();
E se preferisci non caricare il documento in memoria, un equivalente streaming:
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();
Altri suggerimenti
xmllint può farlo e, poiché xmllint è scritto in C ed è un software gratuito, è probabile che sia relativamente semplice per adattare il modo in cui lo fa al tuo programma C #. Ecco un esempio:
% cat foo.xhtml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html [
<!ENTITY D "—">
<!ENTITY o "‘">
<!ENTITY c "’">
<!ENTITY O "“">
<!ENTITY C "”">
]>
<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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow