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 Lecture de fichier XML [ par olibara ] <d travailler sur de l'XML sans créer de fichier [ par simlaboum ] Bonjour, je voudrais traiter des elements XML ( avec des attrubits, des fils...) pour pouvoir ensuite les afficher dans une IHM. Ai-je un autre moye [urgent] enregistrement dans un fichier xml [ par tunit68 ] Bonjour à tous,Je développe une application ou je dois enregistrer des données dans un fichier xml. Or au moment où je fais un "doc.save(monfichier.xm Stocké untableau dans un fichier XML [ par rinuom99 ] salut,je cherche a stocké un tableau de donnée dans un fichier xml et j'arrive pas a le faire, si quelqu'un peu me aidé svp comparer une chaine ? [ par jimmy69 ] Bonjour,Je bosse avec visual studio 2005.J'ai une informations stockee dans un fichier xml de type :".csv,.doc,.html,.txt,.pdf,.ppt,.rtf,.xls";< Copier tous les noeuds d'un fichier XML dans un autre fichier XML [ par TheCatxXx ] Bonjour tout le monde,je suis actuellement en train de faire des tests sur l'XML pour apprendre.J'aimerai connaître la meilleure façon de copier tous Fichier xml en lecture/ecriture [ par renyone ] Salut à tous.Je désirerais ouvrir un fichier xml en lecture/ecriture.Mon fichier est sous la forme suivante:&lt;?xml version="1.0" encoding="utf-8" < lecture fichier xml [ par tunit68 ] bonjour à tous,Je viens de me lancer dans la manipulation des fichiers xml avec c# et je voudrais simplement savoir comment afficher une ligne de mon


Nos sponsors

Sondage...

CalendriCode

Juillet 2009
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

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

Comparez les prix Nouvelle version

Photothèque Nouveau !



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), 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,499 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é.