Create XML file from collection list - c#

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);
}

Related

Load XML containing multiple lists to multiple DataTables

I have an XML that has the below structure:
<?xml version="1.0" encoding="utf-8"?>
<n0:Response xmlns:n0="urn:sap-com:document:sap:rfc:functions">
<Cars>
<item>
<ID>1</ID>
<TYPE>SUV</TYPE>
<YEAR>2022</YEAR>
</item>
<item>
<ID>2</ID>
<TYPE>Convertible</TYPE>
<YEAR>2021</YEAR>
</item>
</Cars>
<Employees>
<item>
<ID>1</ID>
<NAME>John</NAME>
<STATUS>1</STATUS>
<PHONE>000000000</PHONE>
</item>
<item>
<ID>2</ID>
<NAME>Sam</NAME>
<STATUS>2</STATUS>
<PHONE>000000000</PHONE>
</item>
<item>
<ID>3</ID>
<NAME>Jane</NAME>
<STATUS>1</STATUS>
<PHONE>000000000</PHONE>
</item>
</Employees>
</n0:Response>
(this is just a sample, the final file will have more than 10k items per row)
I need to load that file to two DataTables, each having the correct values.
I do this by creating DataSet, loading XML, and filtering the data table.
My DataSet has 3 tables:
but when I try to access the correct data table I get all the items instead of the correct ones (I get items from the entire XML):
var rel = ds.Relations.OfType<DataRelation>()
.FirstOrDefault(x => x.ParentTable.TableName == "Cars")?.ChildTable;
this is the result:
I managed to filter the data by adding a Select statement like below:
var ds = new DataSet();
using Stream stream = new FileStream("Sample.xml", FileMode.Open, FileAccess.Read);
ds.ReadXml(stream);
var table1 = ds.Relations.OfType<DataRelation>()
.FirstOrDefault(x => x.ParentTable.TableName == "Cars")?
.ChildTable.Select("Cars_Id = 0").CopyToDataTable();
var table2 = ds.Relations.OfType<DataRelation>()
.FirstOrDefault(x => x.ParentTable.TableName == "Employees")?
.ChildTable.Select("Employees_Id = 0").CopyToDataTable();
but this isn't generic and I'd like to be able to access the correct DataTable only by name (the node name from XML).
My question is similar to How to get multiple tables in Dataset from XML, but the provided answer didn't solve the issue.

Using LINQ to output SQL data from two tables into XML

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);
}

how to save the results of XPathSelectElements to xml in C#

I have an XML file and I wanna extract some elements using XPathSelectElements("..."). It works fine but I have no idea how to save the extracted data into a new XML file with a new outer wrap
Here's what I've got, XPathSelectElements works fine:
var doc = XDocument.Load("XXX.xml");
var nData = doc.XPathSelectElements("Orders/Order[#ID > 1]");
//code to save data to a new file...
My original xml file is like this:
<?xml version="1.0" encoding="utf-8"?>
<Orders>
<Order ID="1">aaa</Order>
<Order ID="2">bbb</Order>
<Order ID="3">ccc</Order>
</Orders>
And I wanna save the result to a new xml file and with an extra wrap like this:
<?xml version="1.0" encoding="utf-8"?>
<newWrap>
<Orders>
<Order ID="2">bbb</Order>
<Order ID="3">ccc</Order>
</Orders>
</newWrap>
Any help? Thanks a lot~
This is one possible way :
var nData = doc.XPathSelectElements("Orders/Order[#ID > 1]");
var root = new XElement("newWrap",
new XElement("Orders", nData)
);
var newDoc = new XDocument(root);
newDoc.Save("new_file.xml");
Dotnetfiddle Demo

XML DataGrid Where Certain Nodes Are Empty

I am attempting to bind an XML file to a DataGrid. I am only bind the the "Transactions". What I cannot figure out is how to bind only data that has empty nodes. For example, the transaction that has "UserName" of "NSmith" does not have a value for "CustomerFirst".
I want only this child to be bound to the DataGrid
<Root>
<Header>
<value1>0000000</value1>
<value2>1</value2>
<value3>100.00</value3>
</Header>
<Transactions>
<Txn>
<id></id>
<UserName>BSmith</User>
<CustomerFirst>Bob</CustomerFirst>
...
</Txn>
<Txn>
<id></id>
<UserName>NSmith</User>
<CustomerFirst></CustomerFirst>
...
</Txn>
</Transactions>
</Root>
Here is my C# code:
serverPath = Server.MapPath("App_Data/" + xmlFileName);
DataSet dsBillPay = new DataSet();
dsBillPay.ReadXml(serverPath);
dgBillPay.DataSource = dsBillPay.Tables[1];
dgBillPay.DataBind();
The .Tables[1] is selecting the "Transactions".
Now the question is selecting data that has empty nodes.
Thank you in advance.
You can use Linq-to-Xml to filter out elements that have all of their child-elements specified with values and include only those with missing data.
The following example retrieves users that have an empty element but allows AddressTwo to be empty.
string xmlText = #"<Root>
<Header>
<value1>0000000</value1>
<value2>1</value2>
<value3>100.00</value3>
</Header>
<Transactions>
<Txn>
<id>1</id>
<UserName>BSmith</UserName>
<CustomerFirst>Bob</CustomerFirst>
</Txn>
<Txn>
<id>2</id>
<UserName>NSmith</UserName>
<CustomerFirst></CustomerFirst>
</Txn>
<Txn>
<id></id>
<UserName>JSmith</UserName>
<CustomerFirst>James</CustomerFirst>
</Txn>
<Txn>
<id>4</id>
<UserName>KSmith</UserName>
<CustomerFirst>Kevin</CustomerFirst>
<AddressTwo></AddressTwo>
</Txn>
</Transactions>
</Root>";
var root = XElement.Parse(xmlText);
var elementsThatCanBeEmpty = new HashSet<XName>
{
XName.Get("AddressTwo")
};
var transactionsWithoutCustomerFirst =
from transactions in root.Elements(XName.Get("Transactions")).Elements()
where transactions.Elements().Any
(
el =>
String.IsNullOrEmpty(el.Value) &&
!elementsThatCanBeEmpty.Contains(el.Name)
)
select transactions;
foreach(var t in transactionsWithoutCustomerFirst)
{
Console.WriteLine(t.Element(XName.Get("UserName")).Value);
}

how to get root node attribute value using linq

I have the following XML. How to read the root node attribite value and it's decendents using LINQ? I am trying to read "dId" and "dTime" from root node, "id" from Customer element and Order number.
<?xml version="1.0" encoding="utf-8" ?>
<Customers dId="wqwx" dTime="10-9-09 11:23">
<Customer id="1">
<Orders>
<Order number="22" status="ok">
</Orders>
</Customer>
</Customers>
I tried the following code but it doesn't work.
XDocument doc= XDocument.Load(#"C:\Customers.xml");
var q = from c in doc.Descendants("Customers")
select new
{
dID = c.Attribute("dId"),
dTime = c.Attribute("dTime");
}
first, fix your xml (<Order .... />)
then, your linq should look like this....
// .Elements(...) selects all elements of type "Customer"
var q = from c in xDoc.Elements("Customers")
select new
{
dID = c.Attribute("dId"),
dTime = c.Attribute("dTime")
};
you should dl LinqPad... it lets you do Linq queries on the fly, even agains SQL databases. Then, once you get the results you want, copy and past your linq into your source code.
You have to end the order tag with: />
xDoc.Descendants("Customers") should work as well as xDoc.Elements("Customers").
Chris, is there a specific advantage to using .Elements?
You can't use LINQ to access the root tag.
The code below does what you want (I included a well formed xml file as well):
using System;
using System.Linq;
using System.Xml.Linq;
namespace ReadXmlSpike
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Reading file...");
XDocument doc = XDocument.Load("Customers.xml");
var customers =
new
{
DID = (string) doc.Element("Customers").Attribute("did"),
DTime = (DateTime) doc.Element("Customers").Attribute("dTime"),
Customers = from customerxml in doc.Descendants("Customer")
select
new
{
ID = (string)customerxml.Attribute("id"),
Orders = from orderxml in customerxml.Descendants("Order")
select
new
{
Number =(string) orderxml.Attribute("number")
}
}
};
Console.WriteLine("Customersfile with id: {0} and time {1}",customers.DID,customers.DTime);
foreach (var customer in customers.Customers)
{
Console.WriteLine("Customer with id {0} has the following orders:",customer.ID);
foreach (var order in customer.Orders)
{
Console.WriteLine("Order with number {0}",order.Number);
}
}
Console.ReadLine();
}
}
}
and the xml file:
<?xml version="1.0" encoding="utf-8" ?>
<Customers did="www" dTime="10-09-09 11:23">
<Customer id="1">
<Orders>
<Order number="22" status="ok"/>
<Order number="23" status="bad"/>
</Orders>
</Customer>
<Customer id="2">
<Orders>
<Order number="24" status="ok"/>
<Order number="25" status="bad"/>
</Orders>
</Customer>
</Customers>
XDocument d = XDocument.Parse(#"<?xml version='1.0' encoding='utf-8' ?>
<Customers dId='wqwx' dTime='10-9-09 11:23'>
<Customer id='1'>
<Orders>
<Order number='22' status='ok'/>
</Orders>
</Customer>
</Customers>");
var cu = d.Root.Elements().Where(n => n.Name == "Customer");
var c = from cc in cu
select new
{
dId = cc.Document.Root.Attribute("dId").Value,
dTime = cc.Document.Root.Attribute("dTime").Value,
ID = cc.Attribute("id").Value,
number = cc.Element("Orders").Element("Order").Attribute("number").Value
};
foreach (var v in c)
{
Console.WriteLine("dId \t\t= {0}", v.dId);
Console.WriteLine("dTime \t\t= {0}", v.dTime);
Console.WriteLine("CustomerID \t= {0}", v.ID);
Console.WriteLine("OrderCount \t= {0}", v.number);
}
Console Output:
================================
dId = wqwx
dTime = 10-9-09 11:23
CustomerID = 1
OrderCount = 22
请按任意键继续. . .
It does not work the way you wrote it: while printing the above code would complain about anonymous type.
However, with this simple modified version d.Document.Root.Attribute("dId").Value; you can assign it to a string.

Categories

Resources