begin process at 2010 02 10 06:41:46
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Chaîne de caractères

 > PARSER DE NODE XML ALTERNATIF

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];
                    }
                }
            }
        }

    }



 Sources du même auteur

Source avec Zip Source avec une capture Source .NET (Dotnet) DÉBUT DE JEU D'ÉCHECS EN 3D AVEC DIRECTX

 Sources de la même categorie

Source .NET (Dotnet) GREP POUR WINDOWS par Warny
Source avec Zip Source .NET (Dotnet) TEXTBOX SÉQUENCE DE TOUCHES. par vbmaniac8
Source avec Zip Source .NET (Dotnet) WINDOWS FORMS VALIDATORS par sebmafate
Source avec Zip Source .NET (Dotnet) DATE EN TOUTE LETTRE (ARABE) par moi2007
Source avec Zip Source avec une capture Source .NET (Dotnet) COQTEXTTOOLS : TRANSFORMATIONS TEXTE SIMPLE ET UTILISATION A... par coq

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture Source .NET (Dotnet) RECHERCHE ET GESTION DE FICHIERS PERSONNALISÉES par JeremyLecouvert
Source avec Zip Source .NET (Dotnet) AJOUTER PERSONNE DANS UN FICHIER XML par wasssim2005
Source avec Zip Source avec une capture Source .NET (Dotnet) PROTÉGER UN FICHIER XML CONTRE LES MODIFICATIONS FAITES PAR ... par oximoron
Source avec Zip Source .NET (Dotnet) AFFICHER DANS TABLEAU UN FICHER XML par krazymay007
Source avec Zip Source .NET (Dotnet) VALIDATION D'UN FICHIER XML AVEC XSD par Bidou

Commentaires et avis

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?

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

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
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

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,998 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales