Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the fastest way to write XML

I need create XML files frequently and I choose XmlWrite to do the job, I found it spent much time on things like WriteAttributeString ( I need write lots of attributes in some cases), my question is are there some better way to create xml files? Thanks in advance.

like image 510
Hiber Avatar asked Apr 18 '11 13:04

Hiber


2 Answers

Fastest way that I know is two write the document structure as a plain string and parse it into an XDocument object:

string str =
@"<?xml version=""1.0""?>
<!-- comment at the root level -->
<Root>
    <Child>Content</Child>
</Root>";

XDocument doc = XDocument.Parse(str);
Console.WriteLine(doc);

Now you will have a structured and ready to use XDocument object where you can populate with your data. Also, you can even parse a fully structured and populated XML as string and start from there. Also you can always use structured XElements like this:

XElement doc =
  new XElement("Inventory",
    new XElement("Car", new XAttribute("ID", "1000"),
    new XElement("PetName", "Jimbo"),
    new XElement("Color", "Red"),
    new XElement("Make", "Ford")
  )
);
doc.Save("InventoryWithLINQ.xml");

Which will generate:

<Inventory>
  <Car ID="1000">
    <PetName>Jimbo</PetName>
    <Color>Red</Color>
    <Make>Ford</Make>
  </Car>
</Inventory>
like image 83
Teoman Soygul Avatar answered Oct 16 '22 06:10

Teoman Soygul


XmlSerializer

You only have to define hierarchy of classes you want to serialize, that is all. Additionally you can control the schema through some attributes applied to your properties.

like image 40
StanislawSwierc Avatar answered Oct 16 '22 06:10

StanislawSwierc