Reputation: 1121
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.
Upvotes: 0
Views: 1746
Reputation: 183
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");
Upvotes: 0
Reputation: 100527
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();
}
Upvotes: 5