i am very new to this. Hope someone could help me suggest how to improve the code.
I have two tables where i need to get the SQL data and ouput it into XML format. I am using LINQ method. Below how the code looks like.
#region Database XML Methods
private static void CreateDatabaseXml(string path)
{
tbchrDataContext db = new tbchrDataContext();
XDocument doc = new XDocument(
// XML Declaration
new XDeclaration("1.0", "utf-8", "yes"),
// XML Root element to 3rd in nest
new XElement(ns + "WMS",
new XElement(ns + "Order",
new XElement(ns + "Header", from a in db.T_ORDER_DETAILs
select new XElement(ns + "RARefNum", a.RARefNum),
new XElement (ns + "WMSCategory", from b in db.T_ORDER_HEADERs select b.Customer),
new XElement (ns + "CustomerID", from a in db.T_ORDER_DETAILs select a.SupplierName)))) );
#endregion
doc.Save(path);
}
And below how is the output of XML looks like.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<WMS xmlns="http://blog.cripperz.sg">
<Order>
<Header>
<RARefNum>RASO000001</RARefNum>
<RARefNum>RASO000001</RARefNum>
<WMSCategory>ESSVMI</WMSCategory>
<CustomerID>nVidianVidia</CustomerID>
</Header>
</Order>
</WMS>
Ultimately i wanted to achieve the below XML, some of the data grab from SQL is from two separate tables in one XML nest / element.
<?xml version="1.0" encoding="utf-8"?>
<WMS>
<Order>
<Header>
<RARefNum>RASO000001</RARefNum>
<WMSCategory>ESSVMI</WMSCategory>
<CustomerID>nVidia</CustomerID>
<CreationDate>2013-12-02 06:29:50</CreationDate>
<OrderDate>2013-12-02 06:29:50</OrderDate>
<ExpectedShippedDate>2013-12-02 06:29:50</ExpectedShippedDate>
<LastShippedDate>2013-12-02 06:29:50</LastShippedDate>
<CustomerOrderReference>nVidia9338</CustomerOrderReference>
<CustomerShipmentNo>81475721</CustomerShipmentNo>
<CustomerSONo>SO982733</CustomerSONo>
<CustomerInvoiceNo>INV987373</CustomerInvoiceNo>
<CustomerReference1>nVidia 1</CustomerReference1>
<CustomerReference2/>
<WMSReference1>Emp 1</WMSReference1>
<WMSReference2>Emp 2</WMSReference2>
<ShipmentNo>IWU997872</ShipmentNo>
<DocumentNo>KK98764394</DocumentNo>
<Transportation>
<Mode>Freight</Mode>
<VehicleType/>
</Transportation>
<Carrier>
<ID>Fedex</ID>
<Name>Fedex SG</Name>
<Address>Changi Singapore</Address>
<Country/>
<PostalCode/>
<Contact>
<Sequence/>
<Person/>
<Email/>
<DID/>
<Handphone/>
</Contact>
</Carrier>
<Consignee>
<ID>ABC</ID>
<Name>ABC Corp</Name>
<Address>Jurong West, Singapore</Address>
<Country/>
<PostalCode/>
<Contact>
<Sequence/>
<Person/>
<Email/>
<DID/>
<Handphone/>
</Contact>
</Consignee>
<Containers/>
</Header>
<Details>
<Detail>
<LineNo>1</LineNo>
<SKU>SKU0001</SKU>
<SKUDescription>SKU 0001</SKUDescription>
<Package>50</Package>
<OrderedQty>600.000</OrderedQty>
<PickedQty>600.000</PickedQty>
<PickedDate>2013-12-02 06:35:09</PickedDate>
<ShippedQty>600.000</ShippedQty>
<ShippedDate>2013-12-02 06:35:09</ShippedDate>
<ManufactoryDate>2013-12-02 06:35:09</ManufactoryDate>
<ExpiryDate>2014-12-02 06:35:09</ExpiryDate>
<FIFODate>2013-06-02 06:35:09</FIFODate>
<CustomerLotRef1>nVidia 2093</CustomerLotRef1>
<CustomerLotRef2>nVidia 2099</CustomerLotRef2>
<LineReference1>10</LineReference1>
</Detail>
<Detail>
<LineNo>2</LineNo>
<SKU>SKU0002</SKU>
<SKUDescription>SKU 0002</SKUDescription>
<Package>50</Package>
<OrderedQty>100.000</OrderedQty>
<PickedQty>100.000</PickedQty>
<PickedDate>2013-12-02 06:35:09</PickedDate>
<ShippedQty>100.000</ShippedQty>
<ShippedDate>2013-12-02 06:35:09</ShippedDate>
<ManufactoryDate>2013-12-02 06:35:09</ManufactoryDate>
<ExpiryDate>2014-12-02 06:35:09</ExpiryDate>
<FIFODate>2013-06-02 06:35:09</FIFODate>
<CustomerLotRef1>nVidia 2193</CustomerLotRef1>
<CustomerLotRef2>nVidia 2199</CustomerLotRef2>
<LineReference1>10</LineReference1>
</Detail>
</Details>
</Order>
</WMS>
Is there a better way to code it?
In sql server support lot of xml format outputs.
This query returns a xml document from two tables. Maybe you are using
linq, then after completing your sql query, you execute the query from
linq.
select table1.column1, table2.column2 from table1 inner join table2 on table2.table1_id = table1.Id for xml auto
Check this link.
I dont know if this is better but I would probably make some variables instead of calling the linq in the xml. Then you can just call the variable in the xml document.
Something like this maybe:
private static void CreateDatabaseXml(string path)
{
tbchrDataContext db = new tbchrDataContext();
var rARefNum = db.T_ORDER_DETAILs.Select(i => i.RARefNum).Single();
var customer = db.T_ORDER_HEADERs.Select(i => i.Customer).Single();
var supplierName = db.T_ORDER_DETAILs.Select(i => i.SupplierName).Single();
XDocument doc = new XDocument(
// XML Declaration
new XDeclaration("1.0", "utf-8", "yes"),
// XML Root element to 3rd in nest
new XElement(ns + "WMS",
new XElement(ns + "Order",
new XElement(ns + "Header", new XElement(ns + "RARefNum", rARefNum),
new XElement (ns + "WMSCategory", customer),
new XElement (ns + "CustomerID", supplierName)))) );
#endregion
doc.Save(path);
}
Related
I'm trying to build up Xml that looks like the following (taken from another question) but using the XElement/XNamespace classes:
<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>
This is so I can serialize using Newtonsoft.Json.JsonConvert.SerializeXmlNode() and maintain correct arrays.
The problem I'm having is creating json:Array='true'.
Other examples show XmlDocument classes or raw creation of Xml string, but is there a way to achieve it using XElement? I've tried several things with XNamespace to attempt to create the "json" prefix without success.
Yes, you can achieve it with XElement. For example:
XNamespace json = "http://james.newtonking.com/projects/json";
XDocument xml = new XDocument(new XElement("person",
new XAttribute(XNamespace.Xmlns + "json", json),
new XAttribute("id", 1),
new XElement("name", "Alan"),
new XElement("url", "http://www.google.com"),
new XElement("role", new XAttribute(json + "Array", true), "Admin")));
Will produce the following:
<person xmlns:json="http://james.newtonking.com/projects/json" id="1">
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array="true">Admin</role>
</person>
I have a collection string with information about customers like name, gender etc. All custumers have an id.
Now i want to create a common XML file with all customers in it. Something like example below:
<custumers>
<custumer>
<name></name>
<id></id>
<etc></etc>
</custumer>
</custumers>
The start up with no XML file is easy, I used linq to create the xml file.
For initial creation I used following code:
try
{
var xEle = new XElement("Customers",
from cus in cusList
select new XElement("Customer",
new XElement("Name", cus.Name),
new XElement("gender", cus.gender),
new XElement("etc", cus.etc));
}
xEle.Save(path);
But on the point if i want to update the XML file i get some problems to get it.
My approach to solve it:
Iterate over all customers in list and check for all customers if the customer.id exists in the XML.
IF not: add new customer to xml
IF yes: update values
My code so far:
var xEle = XDocument.Load(xmlfile);
foreach (cus in cusList)
try
{
var cids = from cid in xEle.Descendants("ID")
where Int32.Parse(xid.Element("ID").Value) == cus.ID
select new XElement("customer", cus.name),
new XElement ("gender"), cus.gender),
new XELement ("etc."), cus.etc)
);
xEle.Save(xmlpath);
}
How about a different approach....
using System.IO;
using System.Text;
using System.Xml.Serialization;
public void Main()
{
DataSet Custumers = new DataSet("Custumers");
DataTable Custumer = new DataTable("Custumer");
// Create the columns
Custumer.Columns.Add("id", typeof(int)).Unique = true;
Custumer.Columns.Add("name", typeof(string));
Custumer.Columns.Add("gender", typeof(string));
Custumer.Columns.Add("etc", typeof(string));
// Set the primary key
Custumer.PrimaryKey = { Custumer.Columns("id") };
// Add table to dataset
Custumers.Tables.Add(Custumer);
Custumers.AcceptChanges();
// Add a couple of rows
Custumer.Rows.Add(1, "John", "male", "whatever");
Custumer.Rows.Add(2, "Jane", "female", "whatever");
Custumer.AcceptChanges();
// Let's save this to compare to the updated version
Custumers.WriteXml("Custumers_Original.xml");
// Read in XML that contains an existing Custumer and adds a new one
// into a Clone of the Custumer table
DataTable CustumerUpdate = Custumer.Clone;
CustumerUpdate.ReadXml("Custumers_Update.xml");
// Merge the clone table data to the Custumer table
Custumer.Merge(CustumerUpdate);
Custumer.AcceptChanges();
Custumers.WriteXml("Custumers_Final.xml");
}
Custumers_Original.xml looks like this:
<?xml version="1.0" standalone="yes"?>
<Custumers>
<Custumer>
<id>1</id>
<name>John</name>
<gender>male</gender>
<etc>whatever</etc>
</Custumer>
<Custumer>
<id>2</id>
<name>Jane</name>
<gender>female</gender>
<etc>whatever</etc>
</Custumer>
</Custumers>
Custumers_Update.xml has this, making a change to John and adding George:
<?xml version="1.0" encoding="utf-8" ?>
<Custumers>
<Custumer>
<name>John</name>
<id>1</id>
<gender>male</gender>
<etc>this is new</etc>
</Custumer>
<Custumer>
<name>George</name>
<id>3</id>
<gender>male</gender>
<etc>grandson</etc>
</Custumer>
</Custumers>
After the merge, the Custumers_Final.xml contains this:
<?xml version="1.0" standalone="yes"?>
<Custumers>
<Custumer>
<id>1</id>
<name>John</name>
<gender>male</gender>
<etc>this is new</etc>
</Custumer>
<Custumer>
<id>2</id>
<name>Jane</name>
<gender>female</gender>
<etc>whatever</etc>
</Custumer>
<Custumer>
<id>3</id>
<name>George</name>
<gender>male</gender>
<etc>grandson</etc>
</Custumer>
</Custumers>
Also my solution with linq:
try
{
XDocument xEle = XDocument.Load(path);
var ids = from id in xEle.Descendants("Custom")
where id.Element("id").Value == cus.ID
select id;
foreach (XElement idCustom in ids)
{
idCustom.SetElementValue("NewName", "NewElement");
}
xEle.Save(path);
}
I'm trying to write a XML-document programatically.
I need to add <xsd:schema> tag to my document.
Currently I have:
var xmlDoc = new XmlDocument();
var root = xmlDoc.CreateElement("root");
xmlDoc.AppendChild(root);
var xsdSchemaElement = xmlDoc.CreateElement("schema");
xsdSchemaElement.Prefix = "xsd";
xsdSchemaElement.SetAttribute("id", "root");
root.AppendChild(xsdSchemaElement);
However, this renders to:
<root>
<schema id="root" />
</root>
How do I get the tag to be <xsd:schema>?
Already tried var xsdSchemaElement = xmlDoc.CreateElement("xsd:schema"); which simply ignores the xsd:.
Edit #1
Added method
private static XmlSchema GetTheSchema(XmlDocument xmlDoc)
{
var schema = new XmlSchema();
schema.TargetNamespace = "xsd";
return schema;
}
which is called like xmlDoc.Schemas.Add(GetTheSchema(xmlDoc)); but does not generate anything in my target XML.
Using LINQ-to-XML, you can nest XElements and XAttributess in a certain hierarchy to construct an XML document. As for namespace prefix, you can use XNamespace.
Notice that every namespace prefix, such as xsd in your case, has to be declared before it is used, something like xmlns:xsd = "http://www.w3.org/2001/XMLSchema".
XNamespace xsd = "http://www.w3.org/2001/XMLSchema";
var doc =
new XDocument(
//root element
new XElement("root",
//namespace prefix declaration
new XAttribute(XNamespace.Xmlns+"xsd", xsd.ToString()),
//child element xsd:schema
new XElement(xsd + "schema",
//attribute id
new XAttribute("id", "root"))));
Console.WriteLine(doc.ToString());
output :
<root xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:schema id="root" />
</root>
I have the following code:
XNamespace testNM = "urn:lst-emp:emp";
XDocument xDoc;
string path = "project_data.xml";
if (!File.Exists(path))
{
xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(testNM + "Test")
);
}
else
{
xDoc = XDocument.Load(path);
}
var element = new XElement("key",
new XElement("Type", type),
new XElement("Value", value));
xDoc.Element(testNM + "Test").Add(element);
// Save to Disk
xDoc.Save(path);
which produces an output in the XML file like this:
<?xml version="1.0" encoding="utf-16"?>
<Test xmlns="urn:lst-emp:emp">
<key xmlns="">
<Type>String</Type>
<Value>somestring</Value>
</key>
</Test>
How can I get an output like this in the XML file instead?
<?xml version="1.0" encoding="utf-16"?>
<Tests xmlns="urn:lst-emp:emp">
<key name="someString">
<Type>String</Type>
<Value>somestring</Value>
</key >
</Tests>
Note its only the 3rd line that has changed in the XML file.
You can do it this way:
var element = new XElement("key",
new XAttribute("name", "someString"),
new XElement("Type", "type"),
new XElement("Value", "value"));
To provide a complete version of Bilyukov's answer, this should produce the output expected. Obviously substitute the "someString" static string with a variable populated as you wish. Changes include using XName.Get(string, string) to create the appropriate XName objects for the XElement constructors.
XNamespace testNM = "urn:lst-emp:emp";
XDocument xDoc;
string path = "project_data.xml";
if (!File.Exists(path))
{
xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(XName.Get("Tests", testNM.NamespaceName))
);
}
else
{
xDoc = XDocument.Load(path);
}
var element = new XElement(XName.Get("key", testNM.NamespaceName),
new XAttribute("name", "someString"),
new XElement("Type", type),
new XElement("Value", value));
xDoc.Element(XName.Get("Tests", testNM.NamespaceName)).Add(element);
// Save to Disk
xDoc.Save(path);
Your XML has default namespace. Descendants of the element where default namespace declared is considered in the same default namespace, unless it is explicitly declared with different namespace. That's why you need to use the same XNamespace for <key> element. :
var element = new XElement(testNM +"key",
new XAttribute("name", "someString"),
new XElement(testNM +"Type", type),
new XElement(testNM +"Value", value));
I'm trying to create a RSS 2.0 feed in ASP.NET C# with products to provide to Froogle.
The RSS feed should look like:
http://www.google.com/support/merchants/bin/answer.py?answer=160589&hl=en
I'm using the SyndicationFeed and SyndicationsItems to create the feed. But I'm having trouble adding the extra elements like g:image_link.
I try the extra elements like;
syndicationItem.ElementExtensions.Add(new XElement("image_link", product.ImageLink).CreateReader());
This works, but how can I add the namespace
xmlns:g="http://base.google.com/ns/1.0"
to the first RSS tag and use this for the extension elements?
Thank you
I just wrote something like this last week, as a matter of fact. I didn't have much time, so it's not optimized or pretty.
I used an XDocument, though.
static XDocument GetXDocument(List<GoogleProduct> googleProducts)
{
XNamespace gns = "http://base.google.com/ns/1.0";
XDocument document = new XDocument(
new XElement("rss",
new XAttribute("version", "2.0"),
new XAttribute(XNamespace.Xmlns + "g", gns),
new XElement("channel",
new XElement("title", "X Company Feed"),
new XElement("description", "X Description"),
new XElement("link", "http://www.somecompany.com/"),
from googleProduct in googleProducts
select new XElement("item",
new XElement("title", googleProduct.Title),
new XElement(gns + "brand", googleProduct.ProductRecommendedAttributes.Brand),
new XElement(gns + "manufacturer", googleProduct.ProductRecommendedAttributes.Manufacturer),
new XElement(gns + "condition", googleProduct.Condition),
new XElement("description", googleProduct.Description),
new XElement(gns + "id", googleProduct.ID),
from img in googleProduct.ProductRecommendedAttributes.ImageLinks
select new XElement(gns + "image_link", img),
new XElement("link", googleProduct.Link),
new XElement(gns + "price", googleProduct.Price.ToString("0.00")),
new XElement(gns + "product_type", googleProduct.ProductRecommendedAttributes.ProductType),
from pmt in googleProduct.ProductOptionalAttributes.PaymentAccepteds
select new XElement(gns + "payment_accepted", pmt)))));
//
return document;
}
(FYI: GoogleProduct is just a temporary mapper class I used)
It will generate a document along these lines
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">
<channel>
<title>Blah Data Feed</title>
<description>Stuff from Blah</description>
<link>http://www.blah.com/shopping</link>
<item>
<title>Blah</title>
<g:brand>Blah</g:brand>
<g:manufacturer>Blah</g:manufacturer>
<g:condition>New</g:condition>
<description>blah blah</description>
<g:id>268</g:id>
<g:image_link>http://www.blah.com/shopping/images/PRODUCT/medium/268.jpg</g:image_link>
<link>http://www.blah.com/</link>
<g:price>1747.00</g:price>
<g:product_type>Blah Blah</g:product_type>
<g:payment_accepted>Cash</g:payment_accepted>
<g:payment_accepted>Check</g:payment_accepted>
<g:payment_accepted>Visa</g:payment_accepted>
<g:payment_accepted>Mastercard</g:payment_accepted>
</item>
<item>
<title>Blah</title>
<g:brand>Blah</g:brand>
<g:manufacturer>Blah</g:manufacturer>
<g:condition>New</g:condition>
<description>blah blah</description>
<g:id>269</g:id>
<g:image_link>http://www.blah.com/shopping/images/PRODUCT/medium/269.jpg</g:image_link>
<link>http://www.blah.com/</link>
<g:price>1103.00</g:price>
<g:product_type>blah blah</g:product_type>
<g:payment_accepted>Cash</g:payment_accepted>
<g:payment_accepted>Check</g:payment_accepted>
<g:payment_accepted>Visa</g:payment_accepted>
<g:payment_accepted>Mastercard</g:payment_accepted>
</item>
</channel>
</rss>
XElements have great namespace support. Create your first element like this:
XNamespace aw = "http://base.google.com/ns/1.0";
XElement root = new XElement(aw + "image_link", product.ImageLink);
This will give you XML like this:
<image_link xmlns="http://base.google.com/ns/1.0">
</image_link>
Each subsequent element should also use the same namespace. If you want to use namespace prefixes for your elements, it's a similar approach. You can check out some full examples on MSDN here:
How to: Create a Document with Namespaces