Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

PARSER DE NODE XML ALTERNATIF


Information sur la source

Description

Ce petit code est capable de parser une ligne XML genre:
<node foo="bar" lol="ok" />
Ou
<node foo="bar" lol="ok">hello world</node>

Il n'effectue pas de contrôle sur la validité du XML d'une ligne et se veut donc très rapide. J'en avais besoin car les classes XML de Microsoft sont très strictes sur le respect du standard XML.
 

Source

  • /*************************************
  • * XmlNodeReader *
  • * ***********************************
  • * A fast, non validating, in-line *
  • * XML Node reader *
  • * *
  • * Author: Tony POTTIER *
  • * Contact: contact@tonypottier.info *
  • * CODE IS COPYLEFT, USE AT YOUR *
  • * OWN RISKS. *
  • *************************************/
  • public enum XmlNodeType
  • {
  • Opening,
  • Closing
  • }
  • [Serializable()]
  • public class XmlNodeReader
  • {
  • private Dictionary<string, string> _attributes;
  • private string _line;
  • private XmlNodeType _xmlNodeType;
  • private string _name;
  • private string _innerText;
  • /// <summary>
  • /// The XML node as its string representation
  • /// </summary>
  • public string FullText
  • {
  • get
  • {
  • return _line;
  • }
  • }
  • /// <summary>
  • /// XML node Inner Text (empty if there is none)
  • /// </summary>
  • public string InnerText
  • {
  • get
  • {
  • return _innerText;
  • }
  • }
  • /// <summary>
  • /// XML Node Name
  • /// </summary>
  • public string Name
  • {
  • get
  • {
  • return _name;
  • }
  • }
  • /// <summary>
  • /// Opening or Closing tag.
  • /// Tags ending with "/>" are considered as Opening tags.
  • /// </summary>
  • public XmlNodeType XMLNodeType
  • {
  • get
  • {
  • return _xmlNodeType;
  • }
  • }
  • /// <summary>
  • /// The list of attributes of the XML Node
  • /// </summary>
  • public Dictionary<string, string> Attributes
  • {
  • get
  • {
  • return _attributes;
  • }
  • }
  • /// <summary>
  • /// Get an attribute value of the XML node
  • /// </summary>
  • /// <param name="attribute">The name of the attribute</param>
  • /// <returns>Empty string if attribute does not exist</returns>
  • public string getAttribute(string attribute)
  • {
  • if (_attributes.ContainsKey(attribute))
  • {
  • return _attributes[attribute];
  • }
  • else
  • {
  • return "";
  • }
  • }
  • public XmlNodeReader()
  • {
  • _attributes = new Dictionary<string, string>();
  • }
  • public XmlNodeReader(string line)
  • {
  • _line = line;
  • _attributes = new Dictionary<string, string>();
  • decodeLine();
  • }
  • public void decodeString(string line)
  • {
  • _line = line;
  • decodeLine();
  • }
  • private void decodeLine()
  • {
  • _attributes.Clear();
  • _name = "";
  • _innerText = "";
  • bool tagBegun = false;
  • bool searchAttributeName = false;
  • bool searchAttributeValue = false;
  • bool AttributeValueBegunFound = false;
  • //we're looking for the tag name before
  • //attributes
  • bool searchTagName = true;
  • string currentAttributeName = "";
  • string currentAttributeValue = "";
  • _xmlNodeType = XmlNodeType.Opening;
  • int i;
  • for (i = 0; i < _line.Length; i++)
  • {
  • if (tagBegun)
  • {
  • //test end
  • if (_line[i] == '>')
  • { break; }
  • //search for the tag name before
  • //searching for attributes
  • if (searchTagName)
  • {
  • if (_line[i] == '/')
  • {
  • _xmlNodeType = XmlNodeType.Closing;
  • }
  • else if (_line[i] == ' ' && _name != "")
  • {
  • searchTagName = false;
  • }
  • else
  • {
  • _name += _line[i];
  • }
  • }
  • else
  • {
  • //find a new attribute
  • if (!searchAttributeValue && !searchAttributeName)
  • {
  • if (_line[i] != ' ')
  • {
  • searchAttributeName = true;
  • currentAttributeName += _line[i];
  • }
  • }
  • else if (searchAttributeName && !searchAttributeValue)
  • {
  • //look for '=' wich is the end of attribute name
  • if (_line[i] == '=')
  • {
  • searchAttributeName = false;
  • searchAttributeValue = true;
  • _attributes.Add(currentAttributeName.Trim(), "");
  • }
  • else
  • {
  • currentAttributeName += _line[i];
  • }
  • }
  • else if (!searchAttributeName && searchAttributeValue)
  • {
  • if (AttributeValueBegunFound)
  • {
  • if (_line[i] == '"')
  • {
  • //END OF VALUE PARSING
  • AttributeValueBegunFound = false;
  • searchAttributeValue = false;
  • searchAttributeName = false;
  • _attributes[currentAttributeName.Trim()] = currentAttributeValue;
  • currentAttributeName = "";
  • currentAttributeValue = "";
  • }
  • else
  • {
  • currentAttributeValue += _line[i];
  • }
  • }
  • else
  • {
  • //try to find the first " to start value parsing
  • if (_line[i] == '"')
  • { AttributeValueBegunFound = true; }
  • }
  • }
  • }
  • }
  • else if (_line[i] == '<')
  • { tagBegun = true; }
  • }
  • //now decode inner text if it exists
  • if (_line.Length + 1 > i)
  • {
  • for (i = i + 1; i < _line.Length; i++)
  • {
  • if (_line[i] == '<')
  • { break; }
  • else
  • {
  • _innerText += _line[i];
  • }
  • }
  • }
  • }
  • }
/*************************************
     * XmlNodeReader                     *
     * ***********************************
     * A fast, non validating, in-line   *
     * XML Node reader                   *
     *                                   *
     * Author: Tony POTTIER              *
     * Contact: contact@tonypottier.info *
     * CODE IS COPYLEFT, USE AT YOUR     *
     * OWN RISKS.                        *
     *************************************/

    public enum XmlNodeType
    {
        Opening,
        Closing
    }

    [Serializable()]
    public class XmlNodeReader
    {
        private Dictionary<string, string> _attributes;
        private string _line;
        private XmlNodeType _xmlNodeType;
        private string _name;
        private string _innerText;


        /// <summary>
        /// The XML node as its string representation
        /// </summary>
        public string FullText
        {
            get
            {
                return _line;
            }
        }

        /// <summary>
        /// XML node Inner Text (empty if there is none)
        /// </summary>
        public string InnerText
        {
            get
            {
                return _innerText;
            }
        }

        /// <summary>
        /// XML Node Name
        /// </summary>
        public string Name
        {
            get
            {
                return _name;
            }
        }

        /// <summary>
        /// Opening or Closing tag.
        /// Tags ending with "/>" are considered as Opening tags.
        /// </summary>
        public XmlNodeType XMLNodeType
        {
            get
            {
                return _xmlNodeType;
            }
        }

        /// <summary>
        /// The list of attributes of the XML Node
        /// </summary>
        public Dictionary<string, string> Attributes
        {
            get
            {
                return _attributes;
            }
        }

        /// <summary>
        /// Get an attribute value of the XML node
        /// </summary>
        /// <param name="attribute">The name of the attribute</param>
        /// <returns>Empty string if attribute does not exist</returns>
        public string getAttribute(string attribute)
        {
            if (_attributes.ContainsKey(attribute))
            {
                return _attributes[attribute];
            }
            else
            {
                return "";
            }
        }

        public XmlNodeReader()
        {
            _attributes = new Dictionary<string, string>();
        }

        public XmlNodeReader(string line)
        {
            _line = line;
            _attributes = new Dictionary<string, string>();

            decodeLine();
        }

        public void decodeString(string line)
        {
            _line = line;
            decodeLine();
        }

        private void decodeLine()
        {
            _attributes.Clear();
            _name = "";
            _innerText = "";
            bool tagBegun = false;

            bool searchAttributeName = false;
            bool searchAttributeValue = false;
            bool AttributeValueBegunFound = false;

            //we're looking for the tag name before
            //attributes
            bool searchTagName = true;

            string currentAttributeName = "";
            string currentAttributeValue = "";

            _xmlNodeType = XmlNodeType.Opening;

            int i;
            for (i = 0; i < _line.Length; i++)
            {
                if (tagBegun)
                {
                    //test end
                    if (_line[i] == '>')
                    { break; }

                    //search for the tag name before
                    //searching for attributes
                    if (searchTagName)
                    {
                        if (_line[i] == '/')
                        {
                            _xmlNodeType = XmlNodeType.Closing;
                        }
                        else if (_line[i] == ' ' && _name != "")
                        {
                            searchTagName = false;
                        }
                        else
                        {
                            _name += _line[i];
                        }
                    }
                    else
                    {

                        //find a new attribute
                        if (!searchAttributeValue && !searchAttributeName)
                        {
                            if (_line[i] != ' ')
                            {
                                searchAttributeName = true;
                                currentAttributeName += _line[i];
                            }
                        }
                        else if (searchAttributeName && !searchAttributeValue)
                        {
                            //look for '=' wich is the end of attribute name
                            if (_line[i] == '=')
                            {
                                searchAttributeName = false;
                                searchAttributeValue = true;
                                _attributes.Add(currentAttributeName.Trim(), "");
                            }
                            else
                            {
                                currentAttributeName += _line[i];
                            }
                        }
                        else if (!searchAttributeName && searchAttributeValue)
                        {
                            if (AttributeValueBegunFound)
                            {
                                if (_line[i] == '"')
                                {
                                    //END OF VALUE PARSING
                                    AttributeValueBegunFound = false;
                                    searchAttributeValue = false;
                                    searchAttributeName = false;
                                    _attributes[currentAttributeName.Trim()] = currentAttributeValue;
                                    currentAttributeName = "";
                                    currentAttributeValue = "";
                                }
                                else
                                {
                                    currentAttributeValue += _line[i];
                                }
                            }
                            else
                            {
                                //try to find the first " to start value parsing
                                if (_line[i] == '"')
                                { AttributeValueBegunFound = true; }
                            }

                        }
                    }
                }
                else if (_line[i] == '<')
                { tagBegun = true; }
            }

            //now decode inner text if it exists
            if (_line.Length + 1 > i)
            {
                for (i = i + 1; i < _line.Length; i++)
                {
                    if (_line[i] == '<')
                    { break; }
                    else
                    {
                        _innerText += _line[i];
                    }
                }
            }
        }

    }

Commentaires et avis

signaler à un administrateur
Commentaire de bubbathemaster le 19/04/2008 12:54:29

Il y a un truc que je n'ai pas réussi à faire...

Dans les classes Microsoft, pour acceder à un attribut, on fait

node["truc"]

Avec mon code, on fait node.Attributes["truc"] ce qui n'est pas aussi pratique !

Comment on peut avoir ce comportement?

signaler à un administrateur
Commentaire de coq le 19/04/2008 16:44:34 administrateur CS

Salut,

Il s'agit d'un indexeur : http://msdn2.microsoft.com/fr-fr/library/2549tw02(VS.80).aspx

Ajouter un commentaire

Discussions en rapport avec ce code source dans le forum

Probleme parcourir fichier XML [ par ChamY ] Bonjour, J'ai un probleme pour parcourir un fichier XML.J'ai bien lu pas mal de tuto, mais je bloque.Voila ma methode :Le fichier XML est créé de la f Lecture d'un fichier XML - ReadToDescendant(string) [ par billou_13 ] Bonjour, J'aurais une petite question technique concernant la lecture d'un fichier XML et notamment de la méthode ReadToDescendant(string). Je prendr XML, DataSet, Accents et encodage [ par bossun ] Salut, J'ai un fichier XML qui contient des informations sur des chaines de connexion. J'ai crée un DataSet pour pouvoir manipuler ce fichier... tout Problème de lecture fichier XML [ par spotlessmind50 ] Bonjour,je viens vers vous car j'ai un soucis lors du LoadXml, il me retourne une execption comme quoi il ne supporte pas l'encodage xml car mon en te Insertion balise dans fichier XML projet C# [ par Vic9238 ] Bonjour,je réalise un projet en C#, dans lequel je sélectionne des fichiers XML déjà existant.Je cherche à insérer une balise dans les fichiers XML qu Parser de XML [ par bubbathemaster ] Bonjour,Je recherche un parser de XML simple capable de lire node par node un fichier.En effet, je dois travailler avec des fichiers XML pas toujours Codage binaire dans fichier XML [ par themaste ] Bonjour à tous, Mon but est de pouvoir écrire un XML, et dans un des attributs, définir les data binaire d'un fichier (image, ou exe etc...). Pour xml+datagrid +dataset [ par ginfo ] Salut  tout le monde ,puisque chui debutant j'ai un petit probleme  concernant l'affichage d'un fichier xml dans datagrid en passant par dataset , voi exemple pour lire fichier voice xml [ par tkd1984 ] bonjourje veux lire un fichier vsmx(voice xml) à l'aide d'une application c# ,j'ai cherché partout mais il y a rien,je veux des exemples simples qui l Remplir plusieurs datagridview à partir d'un même fichier xml [ par SPN2B ] BonjourJ'ai une interface avec 4 DataGridView. Je veux les remplir à l'aide d'un fichier Xml. J'utilise un DataSet.Le problème est que je ne sais pas


Nos sponsors

Sondage...

CalendriCode

Octobre 2008
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

Logiciels à télécharger sur le même thème :



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel BAÏSE, Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,38 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.