Como resolver todas as referências de entidade em XML e criar um novo XML em C #?

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

  •  03-07-2019
  •  | 
  •  

Pergunta

Como posso resolver todas as referências de entidade no documento XHTML e convertê-lo em documento XHTML claro que o IE pode entender? O exemplo 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>
Foi útil?

Solução

Acontece que isso é simples opção no XmlTextReader (e XmlValidatingReader) classe -. "EntityHandling"

Assim, uma simples demonstração do seu 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 você prefere não ter que carregar o documento para a memória, a transmissão equivalente:

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

Outras dicas

xmllint pode fazê-lo e, desde xmllint é escrito em C e é software livre, é provável relativamente fácil para se adaptar a maneira como ele faz isso para o seu programa C #. Aqui está um exemplo:

% 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>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top