Calendrier

Décembre 2009
L M M J V S D
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
<< < > >>

Présentation

Recherche

W3C

  • Flux RSS des articles

Xml et DotNet

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Trier + Filtrer ses nœuds Xml
+ utiliser des paramètres  tout cela dans les expressions XPath
I - Tri
1 - Trie sur un XmlElement Texte > XmlDataType.Text
 
XPathDocument oXPathDocument = new XPathDocument(System.IO.Path.Combine(Environment.CurrentDirectory, "Contacts.xml"));
            XPathNavigator oXPathNavigator = oXPathDocument.CreateNavigator();
 
            XPathExpression oXPathExpression = oXPathNavigator.Compile("/Contacts/Contact");
            oXPathExpression.AddSort("FirstName", XmlSortOrder.Descending, XmlCaseOrder.None, "", XmlDataType.Text);
 
            XPathNodeIterator oXPathNodeIterator = oXPathNavigator.Select(oXPathExpression);
            while (oXPathNodeIterator.MoveNext())
            {
                listBox1.Items.Add(oXPathNodeIterator.Current.Value);
            }
 
2 - Trie sur un XmlElement nombre > XmlDataType.Number
XPathDocument oXPathDocument = new XPathDocument(System.IO.Path.Combine(Environment.CurrentDirectory, "Contacts.xml"));
            XPathNavigator oXPathNavigator = oXPathDocument.CreateNavigator();
 
            // XPathExpression
            XPathExpression oXPathExpression = oXPathNavigator.Compile("/Contacts/Contact");
            oXPathExpression.AddSort("Other/Age", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
 
            XPathNodeIterator oXPathNodeIterator = oXPathNavigator.Select(oXPathExpression);
            while (oXPathNodeIterator.MoveNext())
            {
                listBox1.Items.Add(oXPathNodeIterator.Current.Value);
            }
 
3 - Tri sur Attribut
XPathDocument oXPathDocument = new XPathDocument(System.IO.Path.Combine(Environment.CurrentDirectory, "Contacts.xml"));
            XPathNavigator oXPathNavigator = oXPathDocument.CreateNavigator();
 
            // XPathExpression
            XPathExpression oXPathExpression = oXPathNavigator.Compile("/Contacts/Contact");
            oXPathExpression.AddSort("@ID", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
 
            XPathNodeIterator oXPathNodeIterator = oXPathNavigator.Select(oXPathExpression);
            while (oXPathNodeIterator.MoveNext())
            {
                listBox1.Items.Add(oXPathNodeIterator.Current.Value);
            }
 
 
Note :
L’expression de tri est soit
> une valeur string (en fait expression XPath donnant le chemin vers élément ou attribut servant de champ de tri) exemple :
-          "@ID"
-          "FirstName"
-          "Other/Age"
Ø Soit une XPathExpression
oXPathExpression.AddSort("@ID", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
 
Ø 2 sens de tri
-          XmlSortOrder.Ascending (plus petit nombre vers le plus grand,ordre alphabétique)
-          XmlSortOrder.Descending
Ø Respect de la casse des caractères
Ø La prise en charge de la langue
Ø 2 types de valeurs XmlDataType.Text et XmlDataType.Number
 
II Des paramètres dans ses expressions XPath
Pendant que j’y suis , on peut utiliser des paramètres dans ses expressions XPath un peu comme ce que l’on fait avec les bases de données … l’avantage ? entre autres cela permet d’inserer des caractères tels ‘ dans ces expressions XPath
Voila un bon lien pour mieux comprendre 
il présente 3 méthodes :
- la classique avec string.Format
- une utilisant les variables Xslt
- une utilisant Mvp.xml (projet disponible  sur CodePlex) > http://www.codeplex.com/MVPXML
Un merci aussi à Bidou de CodeS-SourceS grace à qui j’ai su comment trier « dans les règles » une collection de nœuds Xml
Donc la conclusion est simple :
On peut à la fois filtrer les noeuds grace aux expressions XPath (avec utilisation même de paramètres)
mais également trier
(et même ajouter/supprimer bien sur  des nœuds au cours de l’iteration de XPathNodeIterator)
Ce qui donnerait pour exemple (filtre et tri + variables)
public System.Collections.IEnumerable GetContacts(string FirstName)
        {
            XPathExpression oXPathExpression = System.Xml.XPath.XPathExpression.Compile("/Contacts/Contact[starts-with(FirstName, $firstname)]");
        
            CustomContext oCustomContext = new CustomContext();
            oCustomContext.AddVariable("firstname", FirstName);
 
            oXPathExpression.SetContext(oCustomContext);
            oXPathExpression.AddSort("FirstName", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text);
 
            // iteration (les noeuds sont donc ici deja filtres et triés)
            System.Xml.XPath.XPathNavigator oXPathNavigator = oXPathDocument.CreateNavigator();
            System.Xml.XPath.XPathNodeIterator oXPathNodeIterator = oXPathNavigator.Select(oXPathExpression);
 
            while (oXPathNodeIterator.MoveNext())
            {
                yield return oXPathNodeIterator.Current.Value;
            }
        }
 
Le fichier Xml utilisé pour les exemples
<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
 <Contact ID="1">
    <FirstName>eric</FirstName>
    <LastName>Dupond</LastName>
    <Gender>H</Gender>
    <Other>
      <Age>32</Age>
    </Other>
 </Contact>
 <Contact ID="58">
    <FirstName>Jeanne</FirstName>
    <LastName>Dupond</LastName>
    <Gender>F</Gender>
    <Other>
      <Age>20</Age>
    </Other>
 </Contact>
 <Contact ID="30">
    <FirstName>henri</FirstName>
    <LastName>Dumond</LastName>
    <Gender>H</Gender>
    <Other>
      <Age>15</Age>
    </Other>
 </Contact>
 <Contact ID="45">
    <FirstName>Paul</FirstName>
    <LastName>Durand</LastName>
    <Gender>F</Gender>
    <Other>
      <Age>28</Age>
    </Other>
 </Contact>
 <Contact ID="5">
    <FirstName>Luc</FirstName>
    <LastName>D'urand</LastName>
    <Gender>H</Gender>
   <Other>
     <Age>19</Age>
   </Other>
 </Contact>
</Contacts>
 
Et finalement Linq ne devient pas forcement necessaire, surtout que je me rends compte que Linq n’est pas dans tous les cas une avancée, mais la souplesse qu’il apporte dans la sélection des données est quand même très intéressante
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Classe de sérialization Xml « générique en .NET 1.0 »

J’ai déjà posté une classe de sérialization générique pour .NET 2.0 reposant sur les generics
Avec cette classe on peut aussi bien sérializer un objet qu’une collection ,…
Comme je l’ai déjà dit dès que l’on se retrouve en .NET 1.0, si on veut essayer de faire ce que l’on peut faire en .NET 2.0 avec les generics il faut :
-          1 utiliser le type object à la place de «  T » des generics (ex : List<T>)
-          Créer des classes (collection par exemple reposant sur System.Collections.CollectionBase) qui permettront de pallier le manque des méthodes d’extensions(par rapport à C# 3.0) et des methodes utilisant les predicates(par rapport à .NET 2.0)
public class GenericXmlSerializer
    {
        public static void Serialize(object obj, string Path)
        {
            XmlSerializer oXmlSerializer = new XmlSerializer(obj.GetType());
            StreamWriter oStreamWriter = new StreamWriter(Path);
            oXmlSerializer.Serialize(oStreamWriter, obj);
            oStreamWriter.Close();
        }
 
        public static object Deserialize(string Path, Type t)
        {
            XmlSerializer oXmlSerializer = new XmlSerializer(t);
            StreamReader oStreamReader = new System.IO.StreamReader(Path);
            object obj = oXmlSerializer.Deserialize(oStreamReader);
            oStreamReader.Close();
            return obj;
        }
    }
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
XSD Code Generator 1.4.2.1 

un utilitaire qui permet de générér les classes (en vb ou c#) correspondantes à un schéma Xml
> après avoir installer l'utilitaire il suffit d'utiliser l'add in depuis le menu Outils de Visual Studio

http://www.microsoft.com/downloads/details.aspx?FamilyID=89e6b1e5-f66c-4a4d-933b-46222bb01eb0&DisplayLang=en
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[ System.xml.Schema ] - Créer ses schémas Xml en .NET

2  exemples simples
 public void CreateContact()
        {
            // <?xml version="1.0" encoding="utf-8"?>
            //<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            // <xs:element name="Contact">
            //    <xs:complexType>
            //      <xs:sequence>
            //        <xs:element name="ContactName" type="xs:string" />
            //      </xs:sequence>
            //      <xs:attribute name="Genre" use="optional" />
            //    </xs:complexType>
            // </xs:element>
            //</xs:schema>
            System.Xml.Schema.XmlSchema oXmlSchema = new System.Xml.Schema.XmlSchema();
 
            // element
            System.Xml.Schema.XmlSchemaElement oXmlSchemaElementContact = new System.Xml.Schema.XmlSchemaElement();
            oXmlSchemaElementContact.Name = "Contact";
 
            System.Xml.Schema.XmlSchemaComplexType oXmlSchemaComplexTypeOfContact = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence oXmlSchemaSequenceOfContact = new System.Xml.Schema.XmlSchemaSequence();
            oXmlSchemaComplexTypeOfContact.Particle = oXmlSchemaSequenceOfContact;
            oXmlSchemaElementContact.SchemaType = oXmlSchemaComplexTypeOfContact; //< indique l'imbrication du complextype dans l'element
 
            System.Xml.Schema.XmlSchemaElement oXmlSchemaElementContactName = new System.Xml.Schema.XmlSchemaElement();
            oXmlSchemaElementContactName.Name = "ContactName";
            oXmlSchemaElementContactName.SchemaTypeName = new System.Xml.XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");// namespace necessaire sinon le type généré est string et non xs:string
            oXmlSchemaSequenceOfContact.Items.Add(oXmlSchemaElementContactName);
 
            // attribute
            System.Xml.Schema.XmlSchemaAttribute oXmlSchemaAttributeGenre = new System.Xml.Schema.XmlSchemaAttribute();
            oXmlSchemaAttributeGenre.Name = "Genre";
            oXmlSchemaAttributeGenre.Use = System.Xml.Schema.XmlSchemaUse.Optional;
            oXmlSchemaComplexTypeOfContact.Attributes.Add(oXmlSchemaAttributeGenre);
 
            oXmlSchema.Items.Add(oXmlSchemaElementContact);
 
            // sauvegarde
            System.IO.TextWriter oTextWriter = new System.IO.StreamWriter("c:/tests.xsd");
            oXmlSchema.Write(oTextWriter);
        }
        public void CreateContact2()
        {
            //<?xml version="1.0" encoding="utf-8"?>
            //<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            // <xs:element name="Contact" type="CT_Contact" />
            // <xs:complexType name="CT_Contact">
            //    <xs:sequence>
            //      <xs:element name="ContactName" type="xs:string" />
            //    </xs:sequence>
            // </xs:complexType>
            //</xs:schema>
 
            System.Xml.Schema.XmlSchema oXmlSchema = new System.Xml.Schema.XmlSchema();
 
            // 1 element
            System.Xml.Schema.XmlSchemaElement oXmlSchemaElementContact = new System.Xml.Schema.XmlSchemaElement();
            oXmlSchemaElementContact.Name = "Contact";
            oXmlSchemaElementContact.SchemaTypeName = new System.Xml.XmlQualifiedName("CT_Contact");
 
            oXmlSchema.Items.Add(oXmlSchemaElementContact);
 
            // 2 complextype
            System.Xml.Schema.XmlSchemaComplexType oXmlSchemaComplexTypeofContact = new System.Xml.Schema.XmlSchemaComplexType();
            oXmlSchemaComplexTypeofContact.Name = "CT_Contact";
            System.Xml.Schema.XmlSchemaSequence oXmlSchemaSequenceOfContact = new System.Xml.Schema.XmlSchemaSequence();
            oXmlSchemaComplexTypeofContact.Particle = oXmlSchemaSequenceOfContact;
            System.Xml.Schema.XmlSchemaElement oXmlSchemaElementContactName = new System.Xml.Schema.XmlSchemaElement();
            oXmlSchemaElementContactName.Name = "ContactName";
            oXmlSchemaElementContactName.SchemaTypeName = new System.Xml.XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");// namespace necessaire sinon le type généré est string et non xs:string
            oXmlSchemaSequenceOfContact.Items.Add(oXmlSchemaElementContactName);
 
            oXmlSchema.Items.Add(oXmlSchemaComplexTypeofContact);
 
            // sauvegarde
            System.IO.TextWriter oTextWriter = new System.IO.StreamWriter("c:/tests.xsd");
            oXmlSchema.Write(oTextWriter);
        }
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Générer un schéma xml( *.xsd) à partir d’un fichier xml(*.xml)
 
///<summary>
        /// crée le schéma xml correspondant au fichier xml en entrée
        ///</summary>
        ///<param name="InputUri">le chemin vers le fichier xml</param>
        ///<param name="Path">le chemin de sortie vers le schéma xml à créer</param>
        private static void CreateXmlSchema(string InputUri, string Path)
        {
            System.Xml.XmlReader oXmlReader = System.Xml.XmlReader.Create(InputUri);
            System.Xml.Schema.XmlSchemaSet oXmlSchemaSet = new System.Xml.Schema.XmlSchemaSet();
            System.Xml.Schema.XmlSchemaInference oXmlSchemaInference = new System.Xml.Schema.XmlSchemaInference();
 
            oXmlSchemaSet = oXmlSchemaInference.InferSchema(oXmlReader);
            System.IO.TextWriter oTextWriter = new System.IO.StreamWriter(Path);
 
            foreach (System.Xml.Schema.XmlSchema oXmlSchema in oXmlSchemaSet.Schemas())
            {
                oXmlSchema.Write(oTextWriter);
            }
        }
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Schéma Xml – Typer ses données xml


photo2.jpg

Arbre
Déclaration
-          Root
o   Element
o   Attribute
o   complextype
o   simpleType
puis       Element --> compositor(all,choice,sequence) --> element
 
I Déclaration et root + namespace
<?xml version="1.0" encoding="utf-16"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
 
</xs:schema>
 
II Element
A - SimpleType et complexType
Simpletype : ne contient qu’une valeur texte(pas d’éléments,ni attributs)
Complextype : peut posséder d’autres éléments et attributs
B – Format
<xs:element name="Contact"/>
 
-          type=""  type valeur (ex : type="xs:string") ou pointant vers un simpleType(type="ST_Gender" ) ou complexType (type="CT_Contact")
Ø le type peut être imbriqué
<xs:element name="Contact">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:enumeration value="Man"/>
        <xs:enumeration value="Woman"/>
      </xs:restriction>
    </xs:simpleType>
 </xs:element>
 
Ou contenir un element
<xs:element name="Contacts">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="0" maxOccurs="1" name="Contact" type="CT_Contact"/>
      </xs:sequence>
    </xs:complexType>
 </xs:element>
 
Ø ou pointer vers un complexType ou SimpleType défini en enfant de l’élément root du schéma
        <xs:element minOccurs="0" maxOccurs="1" name="Contact" type="CT_Contact"/>
<xs:complexTypename="CT_Contact">
    <xs:sequence>
      <xs:element name="ContactID" type="xs:int"/>
      <xs:element name="ContactName" type="xs:string"/>
    </xs:sequence>
    <xs:attribute name="Gender" type="ST_Gender"/>
  </xs:complexType>
 
 
C - Cardinalité
(exemple minOccurs="0" maxOccurs="1")
o   minOccurs=""
o   maxOccurs=""
III Attributs d’element
Les attributs doivent être déclarés en dernière position des éléments
<xs:element name="Contact">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ContactFirstName"/>
      </xs:sequence>
      <xs:attribute name="Gender"/>
      <xs:attribute name="Type"/>
    </xs:complexType>
 </xs:element>
Ou
<xs:complexType name="CT_Contact">
    <xs:sequence>
      <xs:element name="ContactID" type="xs:int"/>
      <xs:element name="ContactName" type="xs:string"/>
    </xs:sequence>
    <xs:attribute name="Gender" type="ST_Gender"/>
    <xs:attribute name="Type"/>
 </xs:complexType>
 
photo1.JPG
o   type="" - Les attributs ont également un type soit classique ex xsd :string ou pointant vers un simpleType déclaré en enfant du root(en général une énumération)
o    use="" - Un autre attribut utile  ,Valeurs possibles optional,Required,etc.
IV Compositeurs
Les compositors sont encadrés par <xs:complexType></xs:complexType>
xsd: all > les elements enfants peut importe l'ordre
 <xs:element name="Contact">
    <xs:complexType>
      <xs:all>
        <xs:element name="ContactID" type="xs:int"/>
        <xs:element name="ContactName" type="xs:string"/>
        <xs:element name="ContactFirstName" type="xs:string"/>
      </xs:all>
      <xs:attribute name="Gender"/>
    </xs:complexType>
 </xs:element>
 
xsd : choice > l'un (et un seul) des elements enfants
<xs:element name="Contact">
    <xs:complexType>
      <xs:choice>
        <xs:element name="ContactID" type="xs:int"/>
        <xs:element name="ContactName" type="xs:string"/>
        <xs:element name="ContactFirstName" type="xs:string"/>
      </xs:choice>
      <xs:attribute name="Gender"/>
    </xs:complexType>
 </xs:element>
 
Xsd :sequence : les éléments ajoutes seront à définir dans l'ORDRE dans le fichier Xml
<xs:element name="Contact">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ContactID" type="xs:int"/>
        <xs:element name="ContactName" type="xs:string"/>
        <xs:element name="ContactFirstName" type="xs:string"/>
      </xs:sequence>
      <xs:attribute name="Gender"/>
    </xs:complexType>
 </xs:element>
 
V Référencer un group
<xs:element name="Contact">
    <xs:complexType>
      <xs:sequence>
        <xs:group ref="Group1"/>
      </xs:sequence>
    </xs:complexType>
 </xs:element>
 <xs:group name="Group1">
    <xs:sequence>
      <xs:element name="Title"/>
      <xs:element name="ID"/>
    </xs:sequence>
 </xs:group>
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
System.Xml.XmlNamespaceManager + expressions XPath

Lorsqu’un fichier Xml a des namespaces, si on ne les gère pas avec un
XmlNamespaceManager et que l’on essaie de récupèrer avec une « classique » expression Xpath on récupère tout simplement des valeurs nulles
Deux types de namespaces existent :
-    ceux ayant un prefix (ex :  xmlns:xs= « http://www.w3.org/2001/XMLSchema » )
-    ceux qui n’ont pas de prefix (ex : xmlns= «http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet »)
 
Exemple ici je crée une méthode permettant de lire un code snippet, qui a un namespace
Ce namespace n’a pas de prefix donc je vais en  «  créer un »
 
public CodeSnippet GetCodeSnippet(string FileName)
        {
            System.Xml.XmlDocument oXmlDocument = new System.Xml.XmlDocument();
            oXmlDocument.Load(FileName);
 
 
            // 1 créer le XmlNamespaceManager + lui passer le XmlNameTable du XmlDocument
            System.Xml.XmlNamespaceManager oXNamespaceManager = new System.Xml.XmlNamespaceManager(oXmlDocument.NameTable);
            // 2 ajouter le ou les namespaces au XmlNamespaceManager
            // a > couple prefix + url
            // b > si le namespace n'a pas de prefix 
            //     "créer" son propre prefix qui apparaitra dans les expressions XPath (ex ici je crées le prefix "np" que j'utiliserai partout dans mes expressions XPath)
            oXNamespaceManager.AddNamespace("np", "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet");
            CodeSnippet oCodeSnippet = new CodeSnippet();
            oCodeSnippet.FileName = FileName;
 
            // 3 ajouter le prefix correspondant (selon le prefix du Xmlelement) dans toutes les expressions XPath (pas pour les attributs) + le NamespaceManager
            // Header
            System.Xml.XmlNode Title = oXmlDocument.SelectSingleNode("//np:CodeSnippet/np:Header/np:Title", oXNamespaceManager);
            if (Title != null)
                oCodeSnippet.Header.Title = Title.InnerText;
            System.Xml.XmlNode ShortCut = oXmlDocument.SelectSingleNode("//np:CodeSnippet/np:Header/np:ShortCut", oXNamespaceManager);
            if (ShortCut != null)
                oCodeSnippet.Header.ShortCut = ShortCut.InnerText;
            System.Xml.XmlNode Description = oXmlDocument.SelectSingleNode("//np:CodeSnippet/np:Header/np:Description", oXNamespaceManager);
            if (Description != null)
                oCodeSnippet.Header.Description = Description.InnerText;
            System.Xml.XmlNode Author = oXmlDocument.SelectSingleNode("//np:CodeSnippet/np:Header/np:Author", oXNamespaceManager);
            if (Author != null)
                oCodeSnippet.Header.Author = Author.InnerText;
            System.Xml.XmlNode SnippetType = oXmlDocument.SelectSingleNode("//np:CodeSnippet/np:Header/np:SnippetType", oXNamespaceManager);
            if (SnippetType != null)
                oCodeSnippet.Header.SnippetType = (SnippetType)Enum.Parse(typeof(SnippetType), Author.InnerText.ToLower());
 
            //References
            System.Xml.XmlNodeList References = oXmlDocument.SelectNodes("//np:CodeSnippet/np:Snippet/np:References/np:Reference", oXNamespaceManager);
            foreach (System.Xml.XmlNode Reference in References)
            {
                Reference oReferenceOfSnippet = new Reference();
                System.Xml.XmlNode Assembly = Reference.ChildNodes[0];
                if (Assembly != null)
                    oReferenceOfSnippet.Assembly = Assembly.InnerText;
                System.Xml.XmlNode URL = Reference.ChildNodes[1];
                if (URL != null)
                    oReferenceOfSnippet.URL = URL.InnerText;
 
                oCodeSnippet.References.Add(oReferenceOfSnippet);
            }
 
            // Imports
            System.Xml.XmlNodeList Imports = oXmlDocument.SelectNodes("//np:CodeSnippet/np:Snippet/np:Imports/np:Import", oXNamespaceManager);
            foreach (System.Xml.XmlNode Import in Imports)
            {
                Import oImportOfSnippet = new Import();
                Reference oReferenceOfSnippet = new Reference();
                System.Xml.XmlNode Namespace = Import.ChildNodes[0];
                if (Namespace != null)
                    oImportOfSnippet.Namespace = Namespace.InnerText;
 
                oCodeSnippet.Imports.Add(oImportOfSnippet);
            }
 
            // Code
            System.Xml.XmlNode Language = oXmlDocument.SelectSingleNode("//np:CodeSnippet/np:Snippet/np:Code/@Language", oXNamespaceManager);
            if (Language != null)
                oCodeSnippet.Code.Language = (Language)Enum.Parse(typeof(Language), Language.InnerText.ToLower());
            System.Xml.XmlNode Kind = oXmlDocument.SelectSingleNode("//np:CodeSnippet/np:Snippet/np:Code/@Kind", oXNamespaceManager);
            if (Kind != null)
                oCodeSnippet.Code.Kind = Kind.InnerText;
            System.Xml.XmlNode CDATA = oXmlDocument.SelectSingleNode("//np:CodeSnippet/np:Snippet/np:Code", oXNamespaceManager);
            if (CDATA != null)
                oCodeSnippet.Code.CDATA = CDATA.InnerText;
 
 
            return oCodeSnippet;
        }
   
    }
 
 
Par Romagny13
Ecrire un commentaire - Voir les 1 commentaires - Recommander

Altova Xml Spy 2007 faciliterait le travail avec Open Xml

J'ai vu dans un article sur CodeS-SourceS (blogs) que Altova Xml Spy devrait faciliter le développement avec Open Xml
j'ai téléchargé une version d'évaluation de l'outil en question et en effet  on dispose d'une vue dans l'éditeur facilitant le travail sur document word 2007

c'est un excellent outil que xml spy certainement le meilleur pour Xml, même si j'ai tendance à préférer Visual Studio 2005 qui dispose d'excellents outils pour Xml, l'approche est différente mais excellente,on peut générer le schéma d'un fichier xml, débogguer et afficher la sortie xslt avec variables,etc.,mais on peut aussi disposer de l'intellisense simplement  en affectant le schèma au fichier (une fonctionnalité vraiment interessante)

je me demande si Microsoft a prévu quelques chose vis à vis de Visual Studio(Orcas ou futur) ou des outils pour mieux gérer Open Xml car même si l'Open Xml est sensé etre trés simple d'accès,...
altovaxmlspy2007-1.JPG



le lien vers la version d'évaluation en question
http://www.altova.com/features_office_2007.html

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Unifier l’accès aux données XML et Bases de données
Si on y regarde bien en fait rien n’est plus  «  objet » que le Xml
Exemple : un nœud a des nœuds
Ce qui en objet pourrait se trraduire par exemple par une colllection de contacts <contacts> a des contact <contact> (qui ont à leuir tour des attributs etéléments)
Donc ma vision est très simple désormais :
-          Créer une classe accès générique (couche données)
o   pour le Xml       
o    pour les bases de données (avec DbProviderFactory)
-          Une classe EntitySet qui comprendra
o   Une classe collection (avec les principales méthodes – avec plusieurs surcharges – qui permettront de se « connecter » de la même manière à une classe générique Xml ou d’accès à une base de données :méthodes pour charger,ajouter,modifier,supprimer,trier,convertir)
o   Des classes unitaires (avec fields,properties,trie grace à IComparable et IComparer)
Voici un début de ma classe générique de gestion du Xml :
-          Xml très simple avec un accès semblable à ce que l’on fait pour une collection d’objets, les expressions XPath restent une faiblesse il faudrait définir un système de recherche plus par méthodes et index, voir essayer de faire plusieurs classes héritant de de XmlElement,XmlAttribute,etc. de manière à pouvoir faire une requetage comme XLinq c'est-à-dire oXmlHelper.GetElements(xpath).GetElement(1).GetElement(2).GetAttribute(nomattribut) …
-          Génération de requête Xpath à partir d’une treeview
-          Gestion très simple de treeview
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Cs2Xml
{
    public class XmlHelper
    {
        private XmlUtilities _Xml;
 
        public XmlUtilities Xml
        {
            get { return _Xml; }
            set { _Xml = value; }
        }
        private XPathUtilties _XPath;
 
        public XPathUtilties XPath
        {
            get { return _XPath; }
            set { _XPath = value; }
        }
        private XmlTreeNodeUtilities _XmlTreeNode;
 
        public XmlTreeNodeUtilities XmlTreeNode
        {
            get { return _XmlTreeNode; }
           set { _XmlTreeNode = value; }
        }
 
        public XmlHelper()
        {
            _Xml = new XmlUtilities();
            _XPath = new XPathUtilties();
            _XmlTreeNode = new XmlTreeNodeUtilities();
        }
 
        public class XmlUtilities
        {
            private System.Xml.XmlDocument _XmlDocument;
 
            public System.Xml.XmlDocument XmlDocument
            {
                get { return _XmlDocument; }
                set { _XmlDocument = value; }
            }
 
            public XmlUtilities()
            {
                _XmlDocument = new System.Xml.XmlDocument();
            }
 
            public void Load(string FileName)
            {
                _XmlDocument.Load(FileName);
            }
            public void Load(System.IO.Stream oStream)
            {
                _XmlDocument.Load(oStream);
            }
            public void Load(System.IO.TextReader oTextReader)
            {
                _XmlDocument.Load(oTextReader);
            }
            public void Load(System.Xml.XmlReader oXmlReader)
            {
                _XmlDocument.Load(oXmlReader);
            }
            public void LoadXml(string xml)
            {
                _XmlDocument.LoadXml(xml);
            }
            public void Save(string FileName)
            {
                _XmlDocument.Save(FileName);
            }
            public void Save(System.IO.Stream oStream)
            {
                _XmlDocument.Save(oStream);
            }
            public void Save(System.IO.TextWriter oTextWriter)
            {
                _XmlDocument.Save(oTextWriter);
            }
            public void Save(System.Xml.XmlWriter oXmlWriter)
            {
                _XmlDocument.Save(oXmlWriter);
            }
            public System.Xml.XmlElement GetRootElementOfDocument()
            {
                try
                {
                    return _XmlDocument.DocumentElement;
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlElement[] GetElements(string xpath)
            {
                try
                {
                    List<System.Xml.XmlElement> oXmlElements = new List<System.Xml.XmlElement>();
                    System.Xml.XmlNodeList oXmlNodes = _XmlDocument.SelectNodes(xpath);
                    foreach (System.Xml.XmlNode oXmlNode in oXmlNodes)
                    {
                        if (oXmlNode.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            System.Xml.XmlElement oReturnXmlElement = (System.Xml.XmlElement)oXmlNode;
                            oXmlElements.Add(oReturnXmlElement);
                        }
                    }
                    return oXmlElements.ToArray();
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlNodeList GetElementsByTagName(string elementName)
            {
                return _XmlDocument.GetElementsByTagName(elementName);
            }
 
            public System.Xml.XmlElement GetElement(string xpath)
            {
                try
                {
                    System.Xml.XmlElement oXmlElement = null;
                    System.Xml.XmlNode oXmlNode = _XmlDocument.SelectSingleNode(xpath);
                    if (oXmlNode.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        oXmlElement = (System.Xml.XmlElement)oXmlNode;
                    }
                    return oXmlElement;
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlElement GetElementById(string elementId)
            {
                return _XmlDocument.GetElementById(elementId);
            }
 
            public System.Xml.XmlElement GetElementOfElementByTagName(System.Xml.XmlElement oXmlElement, string TagName)
            {
                try
                {
                    System.Xml.XmlElement oReturnXmlElement = null;
                    System.Xml.XmlNodeList oXmlNodes = oXmlElement.ChildNodes;
 
                    foreach (System.Xml.XmlNode oXmlNode in oXmlNodes)
                    {
                        if (oXmlNode.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            if (oXmlNode.Name == TagName)
                            {
                                oReturnXmlElement = (System.Xml.XmlElement)oXmlNode;
                            }
                        }
                    }
                    return oReturnXmlElement;
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlElement[] GetElementsOfElement(System.Xml.XmlElement oXmlElement)
            {
                try
                {
                    List<System.Xml.XmlElement> oXmlElements = new List<System.Xml.XmlElement>();
                    System.Xml.XmlNodeList oXmlNodes = oXmlElement.ChildNodes;
                    foreach (System.Xml.XmlNode oXmlNode in oXmlNodes)
                    {
                        if (oXmlNode.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            System.Xml.XmlElement oReturnXmlElement = (System.Xml.XmlElement)oXmlNode;
                            oXmlElements.Add(oReturnXmlElement);
                        }
                    }
                    return oXmlElements.ToArray();
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlElement GetElementOfElement(System.Xml.XmlElement oXmlElement, string xpath)
            {
                System.Xml.XmlElement oReturnXmlElement = null;
                try
                {
                    System.Xml.XmlNode oXmlNode = oXmlElement.SelectSingleNode(xpath);
                    if (oXmlNode != null)
                        if (oXmlNode.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            oReturnXmlElement = (System.Xml.XmlElement)oXmlNode;
                        }
                    return oReturnXmlElement;
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlElement GetElementOfElement(System.Xml.XmlElement oXmlElement, int nIndex)
            {
                try
                {
                    System.Xml.XmlElement oReturnXmlElement = null;
                    System.Xml.XmlNode oXmlNode = oXmlElement.ChildNodes[nIndex];
                    if (oXmlNode != null)
                        if (oXmlNode.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            oReturnXmlElement = (System.Xml.XmlElement)oXmlNode;
                        }
                    return oReturnXmlElement;
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
 
 
            public System.Xml.XmlElement GetFirstElementOfElement(System.Xml.XmlElement oXmlElement)
            {
                try
                {
                    System.Xml.XmlElement oResultXmlElement = null;
                    System.Xml.XmlNodeList oXmlNodes = oXmlElement.ChildNodes;
                    bool bFirst = true;
                    foreach (System.Xml.XmlNode oXmlNode in oXmlNodes)
                    {
                        if (oXmlNode.NodeType == System.Xml.XmlNodeType.Element && bFirst)
                        {
                            oResultXmlElement = (System.Xml.XmlElement)oXmlNode;
                            bFirst = false;
                        }
                    }
                    return oXmlElement;
 
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlAttributeCollection GetAttributesOfElement(System.Xml.XmlElement oXmlElement)
            {
                try
                {
                    return oXmlElement.Attributes;
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlAttribute GetAttributeOfElement(System.Xml.XmlElement oXmlElement, int nAttribute)
            {
                try
                {
                    return oXmlElement.Attributes[nAttribute];
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlAttribute GetAttributeOfElement(System.Xml.XmlElement oXmlElement, string AttributeName)
            {
                try
                {
                    return oXmlElement.Attributes[AttributeName];
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public string GetValueOfAttribute(System.Xml.XmlAttribute oXmlAttribute)
            {
                try
                {
                    return oXmlAttribute.Value;
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public string GetTextOfElement(string xpath)
            {
                string sResult = string.Empty;
                try
                {
                    System.Xml.XmlNode oXmlNode = _XmlDocument.SelectSingleNode(xpath);
                    if (oXmlNode.HasChildNodes == true && oXmlNode.ChildNodes.Count == 1 && oXmlNode.FirstChild.NodeType == System.Xml.XmlNodeType.Text)
                    {
                        sResult = oXmlNode.FirstChild.Value;
                    }
 
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
                return sResult;
            }
 
            public string GetTextOfElement(System.Xml.XmlElement oXmlElement)
            {
                string sResult = string.Empty;
                try
                {
                    if (oXmlElement.ChildNodes.Count == 1 && oXmlElement.FirstChild.NodeType == System.Xml.XmlNodeType.Text)
                    {
                        sResult = oXmlElement.FirstChild.Value;
                    }
                    return sResult;
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
 
            public System.Xml.XmlNodeList GetXmlNodes(string xpath)
            {
                try
                {
                    return _XmlDocument.SelectNodes(xpath);
                }
                catch (System.Xml.XPath.XPathException ex)
               {
                    throw ex;
                }
            }
 
            public System.Xml.XmlNode GetXmlNode(string xpath)
            {
                try
                {
                    return _XmlDocument.SelectSingleNode(xpath);
                }
                catch (System.Xml.XPath.XPathException ex)
                {
                    throw ex;
                }
            }
             public bool AddElementToParent(System.Xml.XmlElement Parent, System.Xml.XmlElement NewElement)
            {
                bool bResult = false;
                try
                {
                    Parent.AppendChild(NewElement);
                    bResult = true;
                }
                catch
                { }
                return bResult;
            }
 
            public bool InsertNewElementBeforeElement(System.Xml.XmlElement refElement, System.Xml.XmlElement NewElement)
            {
                bool bResult = false;
                try
                {
                    _XmlDocument.InsertBefore(NewElement, refElement);
                    bResult = true;
                }
                catch
                { }
                return bResult;
            }
            public bool InsertNewElementAfterElement(System.Xml.XmlElement refElement, System.Xml.XmlElement NewElement)
            {
                bool bResult = false;
                try
                {
                    _XmlDocument.InsertAfter(NewElement, refElement);
                    bResult = true;
                }
                catch
                { }
                return bResult;
            }
            public bool UpdateElement(System.Xml.XmlElement OldElement, System.Xml.XmlElement NewElement)
            {
                bool bResult = false;
                try
                {
                    OldElement.ParentNode.ReplaceChild(NewElement, OldElement);
                    bResult = true;
                }
                catch
                { }
                return bResult;
            }
            public bool RemoveElement(System.Xml.XmlElement oXmlElement)
            {
                bool bResult = false;
                try
                {
                    System.Xml.XmlNode Parent = oXmlElement.ParentNode;
                    Parent.RemoveChild(oXmlElement);
                    bResult = true;
                }
                catch
               { }
                return bResult;
            }
            public bool RemoveElement(string xpath)
            {
                bool bResult = false;
                try
                {
                    System.Xml.XmlNode oXmlNode = _XmlDocument.SelectSingleNode(xpath);
                    if (oXmlNode.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        System.Xml.XmlNode Parent = oXmlNode.ParentNode;
                        Parent.RemoveChild(oXmlNode);
                        bResult = true;
                    }
                }
                catch
                { }
                return bResult;
            }
            public bool RemoveElements(System.Xml.XmlElement Parent)
            {
                bool bResult = false;
                try
                {
                    Parent.RemoveAll();
                    bResult = true;
                }
                catch
                { }
                return bResult;
            }
        }
 
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
 
        public class XPathUtilties
        {
 
            private List<string> XPathPreparelist;
 
            public XPathUtilties()
            {
                XPathPreparelist = new List<string>();
            }
            public string BuildXpath(System.Windows.Forms.TreeNode oTreeNode)
            {
                string sResult = string.Empty;
                XPathPreparelist.Clear();
                this.IterateTreeNode(oTreeNode);
                XPathPreparelist.Reverse();
                foreach (string s in XPathPreparelist)
                {
                    sResult += s;
                }
 
                return sResult;
            }         
            private void IterateTreeNode(System.Windows.Forms.TreeNode oTreeNode)
            {
                int nIndex = oTreeNode.Index + 1;
                if (oTreeNode is XmlAttributeTreeNode)
                {
                    XPathPreparelist.Add("/" + oTreeNode.Text);
                }
                if (oTreeNode is XmlElementTreeNode)
                {
                    int nLess = 0;
                    if (oTreeNode.Parent != null)
                    {
                        foreach (System.Windows.Forms.TreeNode t in oTreeNode.Parent.Nodes)
                        {
                            if (t is XmlAttributeTreeNode)
                            {
                                nLess += 1;
                            }
                        }
                    }
                    nIndex = nIndex - nLess;
                    XPathPreparelist.Add("/child::node()[" + nIndex.ToString() + "]");
                }
 
                if (oTreeNode.Parent != null)
                {
                    System.Windows.Forms.TreeNode Parent = oTreeNode.Parent;
                    IterateTreeNode(Parent);
                }
            }
        }       

      public class XmlTreeNodeUtilities

        {
            private List<string> XPathPreparelist;
 
            public XmlTreeNodeUtilities()
            {
                XPathPreparelist = new List<string>();
            }
 
            public System.Windows.Forms.TreeNode[] GetTreeNodes(System.Xml.XmlNodeList oXmlNodes)
            {
                List<System.Windows.Forms.TreeNode> oTreenodes = new List<System.Windows.Forms.TreeNode>();
 
                foreach (System.Xml.XmlNode oXmlNode in oXmlNodes)
                {
                    oTreenodes.Add(this.GetXmlElementTreeNode(oXmlNode));
                }
 
                return oTreenodes.ToArray();
            }
            public System.Windows.Forms.TreeNode GetTreeNode(System.Xml.XmlNode oXmlNode)
            {
                return this.GetXmlElementTreeNode(oXmlNode);
            }
 
            private XmlElementTreeNode GetXmlElementTreeNode(System.Xml.XmlNode oXmlNode)
            {
                XmlElementTreeNode oXmlElementTreeNode;
                try
                {
                    oXmlElementTreeNode = new XmlElementTreeNode();
 
                    switch (oXmlNode.NodeType)
                    {
 
                        case System.Xml.XmlNodeType.Document:
                            //
 
                            break;
                        case System.Xml.XmlNodeType.Element:
                            oXmlElementTreeNode.Name = oXmlNode.Name;
                            oXmlElementTreeNode.Text = oXmlNode.Name;
 
                            if (oXmlNode.Attributes != null)
                            {
                                if (oXmlNode.Attributes.Count > 0)
                                {
                                    foreach (System.Xml.XmlAttribute oXmlAttribute in oXmlNode.Attributes)
                                    {
                                        XmlAttributeTreeNode oXmlAttributeTreeNode = new XmlAttributeTreeNode(oXmlAttribute.Name, oXmlAttribute.Name, oXmlAttribute.Name, 3, 3);
 
                                        XmlTextTreeNode oXmlTextTreeNode = new XmlTextTreeNode(oXmlAttribute.Value, 4, 4);
                                        oXmlAttributeTreeNode.Nodes.Add(oXmlTextTreeNode);
 
                                        oXmlElementTreeNode.Nodes.Add(oXmlAttributeTreeNode);
                                    }
                                }
                            }
                            if (oXmlNode.ChildNodes.Count == 1 && oXmlNode.FirstChild.NodeType == System.Xml.XmlNodeType.Text)
                            {
                                XmlTextTreeNode oXmlTextTreeNode = new XmlTextTreeNode(oXmlNode.InnerText, 4, 4);
 
                                oXmlElementTreeNode.Nodes.Add(oXmlTextTreeNode);
                            }
 
                            break;
                        case System.Xml.XmlNodeType.Text:
                            //
                            break;
 
                    }
 
                    foreach (System.Xml.XmlNode oXmlChildNode in oXmlNode.ChildNodes)
                    {
                        if (oXmlChildNode.NodeType != System.Xml.XmlNodeType.Text && oXmlChildNode.NodeType != System.Xml.XmlNodeType.Comment)
                        {
                            XmlElementTreeNode El = GetXmlElementTreeNode(oXmlChildNode);
                            oXmlElementTreeNode.Nodes.Add(El);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return oXmlElementTreeNode;
            }
 
        }
 
        public class XmlTextTreeNode : System.Windows.Forms.TreeNode
        {
            public XmlTextTreeNode()
            {
                this.Text = string.Empty;
                this.ImageIndex = 4;
                this.SelectedImageIndex = 4;
            }
            public XmlTextTreeNode(string Text, int ImageIndex, int SelectedImageIndex)
            {
                this.Text = Text;
                this.ImageIndex = ImageIndex;
                this.SelectedImageIndex = SelectedImageIndex;
            }
        }
 
        public class XmlDocumentTreeNode : System.Windows.Forms.TreeNode
        {
            public XmlDocumentTreeNode()
            {
            }
        }
 
        public class XmlElementTreeNode : System.Windows.Forms.TreeNode
        {
            private string _Value;
 
            public XmlElementTreeNode()
            {
                this.Name = string.Empty;
                this.Text = string.Empty;
                this._Value = string.Empty;
                this.ImageIndex = 1;
                this.SelectedImageIndex = 1;
            }
            public XmlElementTreeNode(string Name, string Text, string Value, int ImageIndex, int SelectedImageIndex)
            {
                this.Name = Name;
                this.Text = Text;
                this._Value = Value;
                this.ImageIndex = ImageIndex;
                this.SelectedImageIndex = SelectedImageIndex;
 
            }
            public string Value
            {
                get { return _Value; }
                set { _Value = value; }
            }
        }
 
        public class XmlAttributeTreeNode : System.Windows.Forms.TreeNode
        {
            private string _Value;
 
            public XmlAttributeTreeNode()
            {
                this.Name = string.Empty;
                this.Text = string.Empty;
                this._Value = string.Empty;
                this.ImageIndex = 2;
                this.SelectedImageIndex = 2;
            }
            public XmlAttributeTreeNode(string Name, string Text, string Value, int ImageIndex, int SelectedImageIndex)
            {
                this.Name = Name;
                this._Value = Value;
                this.Text = Text;
                this._Value = string.Empty;
                this.ImageIndex = ImageIndex;
                this.SelectedImageIndex = SelectedImageIndex;
 
            }
            public string Value
            {
                get { return _Value; }
                set { _Value = value; }
            }
        }
    }
}
 
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

Les sections des fichiers de configuration [.NET 2.0]

key_Text
configuration
location
configSections (type=configSections_type)
configSectionGroup_type
configSections_type
configTypeDefinition
configSection_section
Infinite_or_int
Infinite
small_boolean_Type
boolean_Type
appSettings (vs:help=configuration/appSettings)
assemblyBinding (vs:help=configuration/assemblyBinding)
configProtectedData(vs:help=configuration/configProtectedData)
connectionStrings (vs:help=configuration/connectionStrings)
mscorlib (vs:help=configuration/mscorlib)
runtime(vs:help=configuration/runtime)
satelliteassemblies (vs:help=configuration/satelliteassemblies)
startup (vs:help=configuration/startup)
system.codedom (vs:help=configuration/system.codedom)
system.data (vs:help=configuration/system.data)
system.data.dataset (vs:help=configuration/system.data.dataset)
system.data.odbc(vs:help=configuration/system.data.odbc)
system.data.oledb (vs:help=configuration/system.data.oledb)
system.data.oracleclient (vs:help=configuration/system.data.oracleclient)
system.data.sqlclient(vs:help=configuration/system.data.sqlclient)
system.diagnostics (vs:help=configuration/system.diagnostics)
system.runtime.remoting (vs:help=configuration/system.runtime.remoting)
system.webServer (vs:help=configuration/system.webServer)
system.windows.forms (vs:help=configuration/system.windows.forms)
windows(vs:help=configuration/windows)
system.net (vs:help=configuration/system.net)
system.transactions(vs:help=configuration/system.transactions)
system.web (vs:help=configuration/system.web)
system.xml.serialization (vs:help=configuration/system.xml.serialization)
system.serviceModel (vs:help=configuration/system.serviceModel)
system.serviceModel.activation (vs:help=configuration/system.serviceModel.activation)
system.runtime.serialization (vs:help=configuration/system.runtime.serialization)

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Visual Studio et ses outils XML – un peu plus loin

1- Saisie rapide XML

positonner le curseur à la fin du nom de la balise > presser la touche TAB > la fin de la ligne est générée comme "un snippet" avec la valeur surlignée

2 - Atteindre la définition d'un élémnt depuis le fichier XML (le schéma XSD pour ce fichier XML devant être défini auparavant bien entendu)

clic droit sur le nom de balise > Atteindre la définition > automatiquement on atteint la définition de cet éléément dans le schéma XSD correspondant

3 - Affciher le fichier XML ou seulement la partie sélectionnée dans un Datagrid

sélectionner les noeuds dans le fichier XML > clic droit > Afficher la grille de données

4 - Voir les schémas XSD Microsoft pour les fichiers XSD et XSL

on peut voir le schéma XSD Microsoft pour l'ensemble des éléments disponible pour les schémas XSD et les feuilles de style XSL en cliquant sur  un élément > atteindre la définition

5 - Déboggage XSLT - un peu plus loin

on dispose de toutes les options de déboggage classiques

ex : ajouter un espion > il suffit de cliquer droit sur l'element 'dans expression XPATH) de la feuille de style XSL > ajouter un espion

on peut également voir les valeurs des éléments parcourus dans le panneau variables locales ou en pointant de la souris l'élément de l'expression XPATH

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
ASTUCES AVEC VISUAL STUDIO 2005
INTELLISENSE XML - GENERATION XSD - DEBOGAGE XSLT ET DATASET TYPE
I Fichier Xml et son schéma XSD – disposer de l’intellisense et de la vérifcation de la validité
 
1 – Ouvrir ou Nouveau fichier Xml 
 
 
2 – dans le panneau propriétés > cliquer sur la propriété schéma (bouton avec 3 points) afin de définir le schéma Xml que devra respecter le fichier Xml
Parcourir jusqu’au schéma *.XSD désiré > ouvrir > OK (vérifier que le schéma est bien sélectionné dans la boite « Schémas XSD »)
 
3 – on a désormais l’intellisense dans le fichier Xml , de plus si on ne respecte pas le schéma ,Visual Studio l’indiquera en soulignant les éléments invalides
II Générer le schéma XSD d’un fichier Xml
 
Menu Xml > Créer un schéma
Il suffit ensuite de sauvegarder le schéma (qui s’affiche dans Visual Studio) dans le répertoire désiré, on peut ainsi utiliser ce schéma à sa convenance
III – Fichier Xml et feuille de style XSL – Afficher la sortie XSLT dans un web browser
 
1 -De la même manière on peut sélectionner la feuille de style *.xsl du fichier Xml (depuis le panneau propriétés propriété« feuille de style »> puis clic sur le bouton 3 points > puis parcourir jusqu »au fichier *.xsl désiré > ok)
2 - Afficher la sortie HTML dans un web browser
Menu XML > Afficher la sortie XSLT
 
 
IV Feuille de style XSL et fichier Xml - Déboguer au pas à pas
1 -Ouvrir la feuille de style XSL (*.xsl) désirée – puis définir l’entrée (c'est-à-dire le fichier *.xml qui entrera en jeu dans la transformation XSLT) panneau propriétés propriété « Entrée » > parcourir jusqu’au fichier *.xml > ouvrir
2 -Déboguer >> menu XML > Débogage XSLT
 
3 – on peut faire un pas à pas et voir la sortie HTML générée s’affichée petit à petit
 
V Fichier XSD et DataSet typé
 
 
De plus et pour finir je dirais vous ne l'avez peut etre jamais vu mais en ouvrant n'importe quel schéma XSD (à condition qu'il soit bien formé bien entendu) Visual Studio génére automatiquement un DataSet Typé
clic droit sur projet > ajouter > élément existant > parcourir jusqu'au schéma XSD désiré
un Dataset typé est alors généré - vous pouvez regarder côté Designer.cs le code a bien été généré
 
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Petite étude Xml et Ado
 
XML
DOM + XPATH
Lecture
Permet d’accéder qu’à certaines parties du document Xml (1 ou plusieurs nœuds)
Ecriture
On peut ajouter, modifier,supprimer spécifiquement un ou plusieurs nœuds dans le document Xml existant
sans pour autant tout réécrire le document Xml
ADO
DataReader + executeNonquery
Ce mode s’apparente au système DataReader + executeNonquery pour la mise a jour
 
>> 
Une architecture 2-tiers semble la mieux appropriée à ce mode de fonctionnement, car on est en relation directe avec la source de données, mais l’application qui attaque directement la couche des données, que ce soit une base de données ou un fichier Xml n’est pas très « robuste » car elle ne dispose pas d’une couche métier ou sont stockés localement les données.
Dans le cas de DOM + XPATH on est obligé d’utiliser une architecture 2-tiers, mais pour Ado on peut utiliser une architecture 3-tiers ou n-tiers en offrant ainsi la possibilité de travailler avec un mode lecture mise à jour directes, ou de travailler en local et ensuite mettre l’ensemble des lignes modifiées à jour .
 
 
XML
SAX (XMLREADER) ou Sérialisation Xml
On charge l’ensemble du document en mémoire
Puis lors de la mise à jour on réécrit complètement le document Xml
ADO
DataSet + TableAdapter
Ce mode s’apparente au système DataSet + Fill + Update
 
>> 
Une architecture 3-tiers ou encore mieux n-tiers est tout à fait adaptée à ce mode de fonctionnement , dans un premier temps on charge les données d’une base ou d’un fichier Xml, puis dans un second temps on travaille localement (consultation des données chargées, ajout/modification/suppression d’éléments) et finalement dans un troisième temps on met à jour la source de données (ajout/modification/suppression dans une base de données,réécriture du fichier Xml), cette architecture garanti une robustesse car en cas de problèmes de mise à jour, on a toujours les données en mémoire localement
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

Ecrire rapidement un fichier XSD correspondant a n'importe quel fichier *.xml

OpenFileDialog oOpenFileDialog;
oOpenFileDialog = newOpenFileDialog();
oOpenFileDialog.Filter = "Xml Files (*.xml)|*.xml|All files (*.*)|*.*";
if (oOpenFileDialog.ShowDialog() == DialogResult.OK)
{
DataSet oDataSet;
oDataSet = newDataSet();
oDataSet.ReadXml(oOpenFileDialog.FileName);
//oDataSet.ReadXmlSchema(oOpenFileDialog.FileName);
richTextBox1.Text= oDataSet.GetXmlSchema();
}

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Charger n’importe quel document *.xml et stocker les informations dans une couche métier avant de l’afficher
Plutôt que d’afficher directement en itérant un fichier xml les nodes dans une treeview, j’ai toujours essayer d’avoir une couche métier intermédiaire,afin de rendre l’application plus robuste et mieux structuré voici un bon début de solution :
Le code de la form
 private void button1_Click(object sender, EventArgs e)
        {
            this.OpenXmlFile();
        }
        // Methods
        public void OpenXmlFile()
        {
            OpenFileDialog oOpenFileDialog;
            oOpenFileDialog = new OpenFileDialog();
 
            if (oOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 1 Charger la couche metier
                ManagementXml oManagementXml = this.GetManagementXml(oOpenFileDialog.FileName);
               
                // 2 Afficher les objets métiers
                treeView1.Nodes.Add(Post(oManagementXml));
            }
        }
// 1
        public ManagementXml GetManagementXml(string sXmlFilePath)
        {
            System.Xml.XmlDocument oXmlDocument ;
            oXmlDocument = new System.Xml.XmlDocument();
            oXmlDocument.Load(sXmlFilePath);
            System.Xml.XmlNode oXmlNode = oXmlDocument.DocumentElement;
            return (LoadManagementXml(oXmlNode));
        }
        private ManagementXml LoadManagementXml(System.Xml.XmlNode oXmlNode)
        {
            ManagementXml oManagementXml;
            try
            {
                oManagementXml = new ManagementXml();
                switch(oXmlNode.NodeType)
                {
                    case System.Xml.XmlNodeType.Document:
                        break;
                    case System.Xml.XmlNodeType.Element:
                        oManagementXml.sName = oXmlNode.Name;
                        break;
                    case System.Xml.XmlNodeType.Text:
                        oManagementXml.sName = oXmlNode.InnerText;
                        break;
                    case System.Xml.XmlNodeType.Attribute:
                        oManagementXml.sName = oXmlNode.Name;
                        break;
                }
               
                foreach (System.Xml.XmlNode oXmlChildNode in oXmlNode.ChildNodes)
                {
                    ManagementXml oM = LoadManagementXml(oXmlChildNode);
                    oManagementXml._ManagementXmlCollection.Add(oM);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return (oManagementXml);
        }
 
 
 // 2
        public TreeNode Post(ManagementXml oManagementXml)
        {
            TreeNode oTreeNode;
            oTreeNode = new TreeNode();
            oTreeNode.Text = oManagementXml.sName;
 
            foreach (ManagementXml oM in oManagementXml._ManagementXmlCollection)
            {
                oTreeNode.Nodes.Add(Post(oM));
            }
 
            return oTreeNode;
        }
    }
 
La classe très simple stockant les informations
using System;
using System.Collections.Generic;
using System.Text;
 
namespace TestObjectXml
{
    public class ManagementXmlCollection : System.Collections.Generic.List<ManagementXml>
    {
 
    }
    public class ManagementXml
    {
        public string sName;
        private ManagementXmlCollection m_ManagementXmlCollection;
        public ManagementXml()
        {
            m_ManagementXmlCollection = new ManagementXmlCollection();
        }
        public ManagementXmlCollection _ManagementXmlCollection
        {
            get { return m_ManagementXmlCollection; }
            set { m_ManagementXmlCollection = value; }
        }
 
    }
}
 
 
Exemple je charge un document Excel (sauvegardé au format *.xml)
 
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Créer un blog sur over-blog.com - Contact - C.G.U. - Rémunération en droits d'auteur - Signaler un abus