92 votes

Comment créer un document XML à l'aide de XmlDocument ?

Comment créer un document XML comme celui-ci ?

<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

en utilisant XmlDocument en C#

221voto

Fuex Points 6246

Qu'en est-il :

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) <a href="https://stackoverflow.com/a/7007781/1141063">Un fichier XML valide nécessite-t-il une déclaration xml ?</a>
(2) <a href="https://stackoverflow.com/a/151481/1141063">Quelle est la différence entre String.Empty et "" (chaîne vide) ?</a>


Le résultat est :

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

Mais je vous recommande d'utiliser LINQ to XML qui est plus simple et plus lisible comme ici :

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

2voto

Teo Points 300

Travailler avec un dictionnaire ->le niveau 2 ci-dessus provient d'un dictionnaire dans mon cas (juste au cas où quelqu'un le trouverait utile) En essayant le premier exemple, je suis tombé sur cette erreur : "Ce document a déjà un noeud 'DocumentElement'." J'ai été inspiré par la réponse ici

et j'ai modifié mon code : (xmlDoc. DocumentElement .AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR

foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Les deux versions (1 et 2 dans la boucle foreach) donnent le résultat :

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note : la troisième ligne "même niveau 2" dans le dictionnaire peut aussi être un niveau 2 comme les autres mais je voulais illustrer l'avantage du dictionnaire - dans mon cas, j'avais besoin de niveaux 2 avec des noms différents.

-6voto

user3007872 Points 1
    //all this thing are done on the wcf-service
public string LogIn(string strUsername, string strPassword)
    {
    //create a login using your dataset
        if (daLecturer.LoginLecturer(strUsername).Rows.Count == 1)
        {
            if (daUsers.GetPassword(strUsername,strPassword).Rows.Count == 1)
            {
                strMessage = "Lecturer";
            }
            else
            {
                strMessage = "incorrect details";
            }
        }
        else
        {
            if (daTutors.LoginTutor(strUsername).Rows.Count == 1)
            {
                if (daUsers.GetPassword(strUsername, strPassword).Rows.Count == 1)
                {
                    strMessage = "Tutor";
                }
                else
                {
                    strMessage = "incorrect details";
                }
            }
            else
            {
                if (daStudents.LoginStudent(strUsername).Rows.Count == 1)
                {
                    if (daUsers.GetPassword(strUsername, strPassword).Rows.Count == 1)
                    {
                        strMessage = "Student";
                    }
                    else
                    {
                        strMessage = "incorrect details";
                    }
                }
                else
                {
                    strMessage = "Invalid user credentials";
                }
            }
        }
        return strMessage;
    }   
public void InsertTodo(string ID, string Date, string Time, string Description, string Status)
    {
    //Insert/append data into an xml file
        XmlDocument xmlDoc = new XmlDocument();//create xml doc
        //maps where the file is saved
        xmlDoc.Load(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Todo.xml");
        XmlElement subRoot = xmlDoc.CreateElement("Todo"); //creates elements profile in parent profiles

        //add ID
        XmlElement appendedElementID = xmlDoc.CreateElement("ID");
        XmlText xmlTextID = xmlDoc.CreateTextNode(ID.Trim());
        appendedElementID.AppendChild(xmlTextID);
        subRoot.AppendChild(appendedElementID);
        xmlDoc.DocumentElement.AppendChild(subRoot);

        //add Date
        XmlElement appendedElementDate = xmlDoc.CreateElement("Date");
        XmlText xmlTextDate = xmlDoc.CreateTextNode(Date.Trim());
        appendedElementDate.AppendChild(xmlTextDate);
        subRoot.AppendChild(appendedElementDate);
        xmlDoc.DocumentElement.AppendChild(subRoot);

        //add Time
        XmlElement appendedElementTime = xmlDoc.CreateElement("Time");
        XmlText xmlTextTime = xmlDoc.CreateTextNode(Time.Trim());
        appendedElementTime.AppendChild(xmlTextTime);
        subRoot.AppendChild(appendedElementTime);
        xmlDoc.DocumentElement.AppendChild(subRoot);

        //add Description
        XmlElement appendedElementDescription = xmlDoc.CreateElement("Description");
        XmlText xmlTextDescription = xmlDoc.CreateTextNode(Description.Trim());
        appendedElementDescription.AppendChild(xmlTextDescription);
        subRoot.AppendChild(appendedElementDescription);
        xmlDoc.DocumentElement.AppendChild(subRoot);

        //add Status
        XmlElement appendedElementStatus = xmlDoc.CreateElement("Status");
        XmlText xmlTextStatus = xmlDoc.CreateTextNode(Status.Trim());
        appendedElementStatus.AppendChild(xmlTextStatus);
        subRoot.AppendChild(appendedElementStatus);
        xmlDoc.DocumentElement.AppendChild(subRoot);
        xmlDoc.Save(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Todo.xml");
    }

    public DataSet LoadTodo()
    {
    //Load xml into a dataset and pass it to asp web site for display on a gridview
        DataSet dsTodo = new DataSet();
        dsTodo.ReadXml(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Todo.xml");
        return dsTodo;
    }

    public void ModifyTodo(string ID, string Date, string Time, string Description, string Status)
    {
    //modify the current record in an xml file
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Todo.xml");

        foreach (XmlNode node in xmlDoc.SelectNodes("TodoList/Todo"))
        {
            if (node.SelectSingleNode("ID").InnerText == ID)
            {
                node.SelectSingleNode("Date").InnerText = Date;
                node.SelectSingleNode("Time").InnerText = Time;
                node.SelectSingleNode("Description").InnerText = Description;
                node.SelectSingleNode("Status").InnerText = Status;
            }
        }
        xmlDoc.Save(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Todo.xml");
    }

    public void DeleteTodo(string ID)
    {
    //delete a record in an xml file
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Todo.xml");

        foreach (XmlNode node in xmlDoc.SelectNodes("TodoList/Todo"))
        {
            if (node.SelectSingleNode("ID").InnerText == ID)
            {
                node.ParentNode.RemoveChild(node);
            }

        }
        xmlDoc.Save(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Todo.xml");
    }
    public void Log(string strTable, string strdesc,string date, string time)
    {
    //generate a log for every action performed on the data
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Log.xml");
        XmlElement subRoot = xmlDoc.CreateElement("Item");

        //logTable
        XmlElement appendedElementLogTable = xmlDoc.CreateElement("table");
        XmlText xmlTextlogTable = xmlDoc.CreateTextNode(strTable);
        appendedElementLogTable.AppendChild(xmlTextlogTable);
        subRoot.AppendChild(appendedElementLogTable);
        xmlDoc.DocumentElement.AppendChild(subRoot);

        //logDesc
        XmlElement appendedElementLogDesc = xmlDoc.CreateElement("description");
        XmlText xmlTextlogDesc = xmlDoc.CreateTextNode(strdesc);
        appendedElementLogDesc.AppendChild(xmlTextlogDesc);
        subRoot.AppendChild(appendedElementLogDesc);
        xmlDoc.DocumentElement.AppendChild(subRoot);

        //logDate
        XmlElement appendedElementLogDate = xmlDoc.CreateElement("date");
        XmlText xmlTextlogDate = xmlDoc.CreateTextNode(date);
        appendedElementLogDate.AppendChild(xmlTextlogDate);
        subRoot.AppendChild(appendedElementLogDate);
        xmlDoc.DocumentElement.AppendChild(subRoot);

        //logTime
        XmlElement appendedElementLogTime = xmlDoc.CreateElement("time");
        XmlText xmlTextLogTime = xmlDoc.CreateTextNode(time);
        appendedElementLogTime.AppendChild(xmlTextLogTime);
        subRoot.AppendChild(appendedElementLogTime);
        xmlDoc.DocumentElement.AppendChild(subRoot);

        xmlDoc.Save(@"C:\Users\Chillibite\Documents\Visual Studio 2010\Projects\AMD\DataServices\Log.xml");
    }
public string dtEmployees()
    {
    //generate excel grouped reports
        Class1 connClass = new Class1();
        SqlDataAdapter dta = new SqlDataAdapter("SELECT City, Country, FirstName, LastName, Title FROM Employees ORDER BY City",connClass.nwConnection);
        connClass.nwConnection.Open();
        DataTable dt = new DataTable("pascal");
        dta.Fill(dt);
        connClass.nwConnection.Close();

        Excel.Application xlApp = new Excel.Application();
        xlApp.Visible = true;
        Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(1);
        Excel.Worksheet xlSheet = (Excel.Worksheet)xlWorkBook.Worksheets[1];
        xlSheet.Cells.Rows.Columns.AutoFit();

        string strTempVariable=dt.Rows[0][0].ToString();

        xlSheet.Cells[4, 1] = dt.Rows[0][0].ToString();
        xlSheet.Cells[1, 1] = "Employees group header";

        for (int count = 0; count < dt.Columns.Count;count++ )
        {
            xlSheet.Cells[3, count+1] = dt.Columns[count].ColumnName;// prints column names
        }
        int group=0;
        int total=0;
        int intRow = 5;//manages xlsheet
        for (int counter = 0; counter < dt.Rows.Count;counter++ )
        {
            if (strTempVariable == dt.Rows[counter]["City"].ToString())
            {
                xlSheet.Cells[intRow, 2] = dt.Rows[counter][1];
                xlSheet.Cells[intRow, 3] = dt.Rows[counter][2];
                xlSheet.Cells[intRow, 4] = dt.Rows[counter][3];
                xlSheet.Cells[intRow, 5] = dt.Rows[counter][4];
                group++;
                total++;
                intRow++;
            }
            else
            {
                xlSheet.Cells[intRow, 4] = "group name  " + strTempVariable + "  " + group.ToString();

                strTempVariable = dt.Rows[counter][0].ToString();
                intRow++;
                xlSheet.Cells[intRow, 1] = strTempVariable;
                intRow++;
                counter--;
                group = 0;
            }

        }
        intRow++;
        xlSheet.Cells[intRow, 4] = "group name  " + strTempVariable + "  "+group.ToString();  
        intRow++;
        xlSheet.Cells[intRow, 4] = "GrandTotal  " + "  "+total.ToString();

        xlWorkBook.Close(true, "Mapule", 0);//The name of the worksheet

        xlApp.Quit();

        return "Report Successfully";

    }

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X