简体   繁体   中英

writing elements to an XML file in C#

So I'm attempting to create a large XML file of the form:

<xml>
    <element id ="1">1</element>
    <element id ="2">2</element>
    <element id ="3">3</element>
    ...
    <element id ="100000000">100000000</element>
</xml>

Using C#. I can't seem to find a way to format the element to include the id in the declaration (I am not familiar with XML at all).

Does anyone know how I could do this in C#?

Here is my attempt:

using System;
using System.Xml;
using System.Linq;
using System.Text;

namespace BigXML
{
    class Class1
    {

        static void Main(string[] args)
        {

            // Create a new file in C:\\ dir

            XmlTextWriter textWriter = new XmlTextWriter("C:\\Users\\username\\Desktop\\testBigXmFile.xml", null);
            textWriter.Formatting = Formatting.Indented;
            textWriter.Indentation = 3;
            textWriter.IndentChar = ' ';
            // Opens the document

            textWriter.WriteStartDocument(true);

            textWriter.WriteStartElement("xml");
            // Write comments
            for (int i = 0; i < 100000000; i++)
            {
                textWriter.WriteElementString("element id =" + '"' + i.ToString() + '"', i.ToString());
            }

            textWriter.WriteEndElement();
            textWriter.WriteEndDocument();

            textWriter.Close();

        }

    }
}

Thank you, and have a nice day.

You need to write attribute "id". There are several ways of doing it like XmlWriter.WriteAttributeString

 for (int i = 0; i < 100000000; i++)
 {
    textWriter.WriteStartElement("book"); 
    writer.WriteAttributeString("id", i.ToString());                
    textWriter.WriteString(i.ToString());
    textWriter.WriteEndElement(); 
 }

Also check out System.Xml.Linq . You can perform the same using XDocument like so

XDocument xdocfoo = new XDocument(new XElement("xml"));

for (int i = 0; i < 100; i++)
{
    XElement ele = new XElement("element");
    ele.SetAttributeValue("id", i.ToString());
    ele.Value = i.ToString();
    xdocfoo.Root.Add(ele);
}

xdocfoo.Save(@"c:\foo.xml");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM