I am trying to figure out what the best method is for writing an XML Document. Below is a simple example of what I am trying to create off of data I am pulling from our ERP system. I have read about XMLWriter, but thought I would see if there are any other better methods. Any suggestions would be greatly appreciated.
Example XML:
<?xml version="1.0"?>
<Orders>
<Order OrderNumber="12345">
<ItemNumber>0123993587</ItemNumber>
<QTY>10</QTY>
<WareHouse>PA019</WareHouse>
</Order>
<Order OrderNumber="12346">
<ItemNumber>0123993587</ItemNumber>
<QTY>9</QTY>
<WareHouse>PA019</WareHouse>
</Order>
<Order OrderNumber="12347">
<ItemNumber>0123993587</ItemNumber>
<QTY>8</QTY>
<WareHouse>PA019</WareHouse>
</Order>
</Orders>
If you don't want (or can't) to use
LINQ to XML
, neither to duplicate yourOrder
class to include XML serialization, and thinksXmlWriter
is too much verbose, you can go with plain classicalXmlDocument
class:There are a lot of good suggestions in this thread, but one that hasn't been mentioned: Defining an ADO
DataSet
and serializing/deserializing using theReadXml
andWriteXml
methods. This can be a very simple and attractive solution. Your XML isn't in quite the right format, but it's close.I had to create following XML document having some part of it parametrized.
And here's my code that does this with single LINQ statement.
Make a note that creating XML document above using LINQ and saving it to XML file preserves the XML document formatting and keeps line-breaks and carriage-returns that makes the document properly tabified.
Josh's answer shows how easy it is to create a single element in LINQ to XML... it doesn't show how it's also hugely easy to create multiple elements. Suppose you have a
List<Order>
calledorders
... you can create the whole document like this:LINQ to XML makes constructing XML incredibly easy. It also has support for XML namespaces which is pretty easy too. For instance, if you wanted your elements to be in a particular namespace, you'd just need:
LINQ to XML is the best XML API I've worked with... it's great for querying too.
You just right click on your code window , select InsertSnippet follow this Link
its very easy