g_johnson
asked on
How do I create an XML file with multiple namespaces using C#
I need to produce the following XML file using linq to XML, and the Namespaces and schemalocation are killing me! After hours of research and trial and error, I'm hoping you can help.
As you can see, I need to loop through the product after a table read.
If it weren't for the namespaces and schemalocation, I would do this:
dcROIdc dc = new dcROIdc(this._ConnString);
XDocument doc = new XDocument();
XElement feed = new XElement("feed");
for (int i = 0; i < 10; i++)
{
XElement product = new XElement("product");
XElement SKU = new XElement("SKU");
SKU.Value = "sku_" + i.ToString();
XElement inventory = new XElement("inventory");
XElement quantity = new XElement("quantity");
quantity.Value = i.ToString();
inventory.Add(quantity);
product.Add(SKU);
product.Add(inventory);
feed.Add(product);
}
doc.Add(feed);
and then save the document.
How do I get the namespaces and schemalocation in there?
Thanks!
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.junk.com/xml/mp/inventory/R1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.junk.com/xml/mp/inventory/R1.1 http://support.junk.com/mp/R1.1/product/inventory.xsd">
<product>
<SKU>sku_1</SKU>
<inventory>
<quantity>1</quantity>
</inventory>
</product>
<product>
<SKU>sku_2</SKU>
<inventory>
<quantity>12</quantity>
</inventory>
</product>
</feed>
As you can see, I need to loop through the product after a table read.
If it weren't for the namespaces and schemalocation, I would do this:
dcROIdc dc = new dcROIdc(this._ConnString);
XDocument doc = new XDocument();
XElement feed = new XElement("feed");
for (int i = 0; i < 10; i++)
{
XElement product = new XElement("product");
XElement SKU = new XElement("SKU");
SKU.Value = "sku_" + i.ToString();
XElement inventory = new XElement("inventory");
XElement quantity = new XElement("quantity");
quantity.Value = i.ToString();
inventory.Add(quantity);
product.Add(SKU);
product.Add(inventory);
feed.Add(product);
}
doc.Add(feed);
and then save the document.
How do I get the namespaces and schemalocation in there?
Thanks!
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.junk.com/xml/mp/inventory/R1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.junk.com/xml/mp/inventory/R1.1 http://support.junk.com/mp/R1.1/product/inventory.xsd">
<product>
<SKU>sku_1</SKU>
<inventory>
<quantity>1</quantity>
</inventory>
</product>
<product>
<SKU>sku_2</SKU>
<inventory>
<quantity>12</quantity>
</inventory>
</product>
</feed>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you. That works. Now I'm studying the code to see if I can understand it!!
Not a problem g_johnson, glad to help.
http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.addnamespace(v=vs.110).aspx