Comment résoudre toutes les références d'entités en XML et créer un nouveau XML en C #?

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

  •  03-07-2019
  •  | 
  •  

Question

Comment puis-je résoudre toutes les références d'entité dans le document XHTML et les convertir en document XHTML simple que IE peut comprendre? L'exemple 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>
Était-ce utile?

La solution

Il s’avère que cette option est simple dans la classe XmlTextReader (et XmlValidatingReader) - "EntityHandling".

Donc, une simple démonstration de votre problème:

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

Et si vous préférez ne pas avoir à charger le document en mémoire, un équivalent en continu:

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

Autres conseils

xmllint peut le faire et, étant donné que xmllint est écrit en C et est un logiciel libre, il est probablement relativement facile adapter la façon dont il le fait à votre programme C #. Voici un exemple:

% 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>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top