Question

J'ouvre un fichier XML à l'aide de .NET XmlReader et l'enregistre dans un autre nom de fichier. Il semble que la déclaration DOCTYPE change entre les deux fichiers. Bien que le fichier nouvellement enregistré reste du code XML valide, je me demandais pourquoi il insistait pour changer les balises d'origine.

Dim oXmlSettings As Xml.XmlReaderSettings = New Xml.XmlReaderSettings()
oXmlSettings.XmlResolver = Nothing
oXmlSettings.CheckCharacters = False
oXmlSettings.ProhibitDtd = False
oXmlSettings.IgnoreWhitespace = True

Dim oXmlDoc As XmlReader = XmlReader.Create(pathToOriginalXml, oXmlSettings)
Dim oDoc As XmlDocument = New XmlDocument()
oDoc.Load(oXmlDoc)
oDoc.Save(pathToNewXml)

Ce qui suit (dans le document d'origine):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">

devient (remarquez les caractères [] à la fin):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"[]>
Était-ce utile?

La solution

La bibliothèque analyse probablement l'élément DOCTYPE dans une structure interne, puis reconvertit la structure en texte. Il ne stocke pas la forme de chaîne d'origine.

Autres conseils

Il y a un bogue dans System.Xml lorsque vous définissez XmlDocument.XmlResolver = null. La solution de contournement consiste à créer un XmlTextWriter personnalisé:

    private class NullSubsetXmlTextWriter : XmlTextWriter
    {
        public NullSubsetXmlTextWriter(String inputFileName, Encoding encoding)
            : base(inputFileName, encoding)
        {
        }
        public override void WriteDocType(string name, string pubid, string sysid, string subset)
        {
            if (subset == String.Empty)
            {
                subset = null;
            }
            base.WriteDocType(name, pubid, sysid, subset);
        }
    }

Dans votre code, créez un nouveau NullSubsetXmlTextWriter (pathToNewXml, Encoding.UTF8) et transmettez cet objet à la méthode oDoc.Save ().

Voici le Microsoft. cas de support technique où vous pouvez lire des informations sur la solution de contournement (elle décrit la solution de contournement mais ne fournit pas le code).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top