Related
I want to calculate the formula of a cell and retrieve the calculated value. But it gives #NAME? as the cell value when cell.Calculate() is executed.
var package = new ExcelPackage();
var ws = package.Workbook.Worksheets.Add("Test");
ExcelRange cellTest = ws.Cells[1, 1];
cellTest.Formula = "TRIM( Hello World )";
cellTest.Calculate();
var cellCalculatedValue = cellTest.Value;
Here the cellTest.Value = #NAME?
Remember the Epplus doesnt actually have access to the excel engine, it just generates raw XML files that excel interprets when the file is first opened.
So for Formula, the documentation does say you can use Calculate() to get a value like you could in Excel. But what it doesnt tell you is that it does not support all excel built in functions. And understand that the functions in Epplus/C# are NOT the exact same as what will be ran in Excel. They are simply Epplus's interpretation/copies of what excel has.
If you look at https://github.com/JanKallman/EPPlus/blob/master/EPPlus/FormulaParsing/Excel/Functions/BuiltInFunctions.cs:
namespace OfficeOpenXml.FormulaParsing.Excel.Functions
{
public class BuiltInFunctions : FunctionsModule
{
public BuiltInFunctions()
{
// Text
Functions["len"] = new Len();
Functions["lower"] = new Lower();
Functions["upper"] = new Upper();
Functions["left"] = new Left();
Functions["right"] = new Right();
Functions["mid"] = new Mid();
Functions["replace"] = new Replace();
Functions["rept"] = new Rept();
Functions["substitute"] = new Substitute();
Functions["concatenate"] = new Concatenate();
Functions["char"] = new CharFunction();
Functions["exact"] = new Exact();
Functions["find"] = new Find();
Functions["fixed"] = new Fixed();
Functions["proper"] = new Proper();
Functions["search"] = new Search();
Functions["text"] = new Text.Text();
Functions["t"] = new T();
Functions["hyperlink"] = new Hyperlink();
Functions["value"] = new Value();
// Numbers
Functions["int"] = new CInt();
// Math
Functions["abs"] = new Abs();
Functions["asin"] = new Asin();
Functions["asinh"] = new Asinh();
Functions["cos"] = new Cos();
Functions["cosh"] = new Cosh();
Functions["power"] = new Power();
Functions["sign"] = new Sign();
Functions["sqrt"] = new Sqrt();
Functions["sqrtpi"] = new SqrtPi();
Functions["pi"] = new Pi();
Functions["product"] = new Product();
Functions["ceiling"] = new Ceiling();
Functions["count"] = new Count();
Functions["counta"] = new CountA();
Functions["countblank"] = new CountBlank();
Functions["countif"] = new CountIf();
Functions["countifs"] = new CountIfs();
Functions["fact"] = new Fact();
Functions["floor"] = new Floor();
Functions["sin"] = new Sin();
Functions["sinh"] = new Sinh();
Functions["sum"] = new Sum();
Functions["sumif"] = new SumIf();
Functions["sumifs"] = new SumIfs();
Functions["sumproduct"] = new SumProduct();
Functions["sumsq"] = new Sumsq();
Functions["stdev"] = new Stdev();
Functions["stdevp"] = new StdevP();
Functions["stdev.s"] = new Stdev();
Functions["stdev.p"] = new StdevP();
Functions["subtotal"] = new Subtotal();
Functions["exp"] = new Exp();
Functions["log"] = new Log();
Functions["log10"] = new Log10();
Functions["ln"] = new Ln();
Functions["max"] = new Max();
Functions["maxa"] = new Maxa();
Functions["median"] = new Median();
Functions["min"] = new Min();
Functions["mina"] = new Mina();
Functions["mod"] = new Mod();
Functions["average"] = new Average();
Functions["averagea"] = new AverageA();
Functions["averageif"] = new AverageIf();
Functions["averageifs"] = new AverageIfs();
Functions["round"] = new Round();
Functions["rounddown"] = new Rounddown();
Functions["roundup"] = new Roundup();
Functions["rand"] = new Rand();
Functions["randbetween"] = new RandBetween();
Functions["rank"] = new Rank();
Functions["rank.eq"] = new Rank();
Functions["rank.avg"] = new Rank(true);
Functions["quotient"] = new Quotient();
Functions["trunc"] = new Trunc();
Functions["tan"] = new Tan();
Functions["tanh"] = new Tanh();
Functions["atan"] = new Atan();
Functions["atan2"] = new Atan2();
Functions["atanh"] = new Atanh();
Functions["acos"] = new Acos();
Functions["acosh"] = new Acosh();
Functions["var"] = new Var();
Functions["varp"] = new VarP();
Functions["large"] = new Large();
Functions["small"] = new Small();
Functions["degrees"] = new Degrees();
// Information
Functions["isblank"] = new IsBlank();
Functions["isnumber"] = new IsNumber();
Functions["istext"] = new IsText();
Functions["isnontext"] = new IsNonText();
Functions["iserror"] = new IsError();
Functions["iserr"] = new IsErr();
Functions["error.type"] = new ErrorType();
Functions["iseven"] = new IsEven();
Functions["isodd"] = new IsOdd();
Functions["islogical"] = new IsLogical();
Functions["isna"] = new IsNa();
Functions["na"] = new Na();
Functions["n"] = new N();
// Logical
Functions["if"] = new If();
Functions["iferror"] = new IfError();
Functions["ifna"] = new IfNa();
Functions["not"] = new Not();
Functions["and"] = new And();
Functions["or"] = new Or();
Functions["true"] = new True();
Functions["false"] = new False();
// Reference and lookup
Functions["address"] = new Address();
Functions["hlookup"] = new HLookup();
Functions["vlookup"] = new VLookup();
Functions["lookup"] = new Lookup();
Functions["match"] = new Match();
Functions["row"] = new Row();
Functions["rows"] = new Rows();
Functions["column"] = new Column();
Functions["columns"] = new Columns();
Functions["choose"] = new Choose();
Functions["index"] = new Index();
Functions["indirect"] = new Indirect();
Functions["offset"] = new Offset();
// Date
Functions["date"] = new Date();
Functions["today"] = new Today();
Functions["now"] = new Now();
Functions["day"] = new Day();
Functions["month"] = new Month();
Functions["year"] = new Year();
Functions["time"] = new Time();
Functions["hour"] = new Hour();
Functions["minute"] = new Minute();
Functions["second"] = new Second();
Functions["weeknum"] = new Weeknum();
Functions["weekday"] = new Weekday();
Functions["days360"] = new Days360();
Functions["yearfrac"] = new Yearfrac();
Functions["edate"] = new Edate();
Functions["eomonth"] = new Eomonth();
Functions["isoweeknum"] = new IsoWeekNum();
Functions["workday"] = new Workday();
Functions["networkdays"] = new Networkdays();
Functions["networkdays.intl"] = new NetworkdaysIntl();
Functions["datevalue"] = new DateValue();
Functions["timevalue"] = new TimeValue();
// Database
Functions["dget"] = new Dget();
Functions["dcount"] = new Dcount();
Functions["dcounta"] = new DcountA();
Functions["dmax"] = new Dmax();
Functions["dmin"] = new Dmin();
Functions["dsum"] = new Dsum();
Functions["daverage"] = new Daverage();
Functions["dvar"] = new Dvar();
Functions["dvarp"] = new Dvarp();
//Finance
Functions["pmt"] = new Pmt();
}
}
}
You will see that Trim is not in there, unfortunately. You could, in theory, add it yourself like this:
[TestMethod]
public void Test1()
{
using (var package = new ExcelPackage())
{
package.Workbook.FormulaParserManager.LoadFunctionModule(new MyFunctionModule());
var ws = package.Workbook.Worksheets.Add("Test");
var cellTest = ws.Cells[1, 1];
cellTest.Formula = "TRIM(\"Hello World\")";
ws.Calculate();
var cellCalculatedValue = cellTest.Value; //Will now show a proper value
}
}
public class TrimFunction : ExcelFunction
{
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 1);
var result = arguments.ElementAt(0).Value.ToString().Trim();
return CreateResult(result, DataType.String);
}
}
public class MyFunctionModule : FunctionsModule
{
public MyFunctionModule()
{
Functions.Add("trim", new TrimFunction());
}
}
But, again, it has nothing to do with the actual function in excel - they are completely separate. The TRIM function above will only existing in the C# world. When excel opens the file, it will apply its own TRIM function.
I am trying to build an XML document using Linq, XElement and data from Database,
It's working kinda, but in my XML, I want to close the tag and start a new tag and get the results from the query to populate into for the Tag, it is complaining that my variable r in the tag is unresolved, how can I make this work, or is there a better way of building the XML. All the child elements should be under the parent , having two children and , which has their own set of children.
Here is the code below
public void GenerateXML(int id, string site, string state, string country, string bFn, string bLn, string sFn, string sLn)
{
var results = (from o in _db.Orders
where o.OrderId == id
select o).ToList();
var xmlDoc = new XElement("Order",
from r in results
select
new XElement("OrderHeader",
new XElement("SiteId", site),
new XElement("OrderId", r.OrderId),
new XElement("Time", r.OrderDate.Value),
new XElement("Subtotal", r.SubTotal),
new XElement("Shipping", ""),
new XElement("SalesTax", r.SalesTax),
new XElement("Total", r.Total),
new XElement("PaymentAmount", ""),
new XElement("PaymentMethod", ""),
new XElement("ArchiTypeAcctNum", "20001"),
new XElement("TaxExempt", r.TaxExempt),
new XElement("SpecialInstructions", r.SpecialInstructions),
new XElement("BillTo",
new XElement("BillEmail", r.BillToEmail),
new XElement("FirstName", bFn),
new XElement("LastName", bLn),
new XElement("CompanyName", r.BillCompany),
new XElement("Address1", r.BillToAddress),
new XElement("City", r.BillToCity),
new XElement("State", state),
new XElement("Country", country),
new XElement("Zip", r.BillToZip),
new XElement("Phone", r.BillToPhoneNumber)),
new XElement("ShipTo",
new XElement("FirstName", sFn),
new XElement("LastName", sLn),
new XElement("CompanyName", r.ShipCompany),
new XElement("Address1", r.ShipToAddress),
new XElement("City", r.ShipToCity),
new XElement("State", state),
new XElement("Country", country),
new XElement("Zip", r.ShipToZip),
new XElement("Phone", r.ShipToPhoneNumber))),
new XElement("Items",
from i in r.Items
select new XElement("Item",
new XElement("SKU", i.SkuNumber),
new XElement("PROD_Name", i.ProductName),
new XElement("Description", i.Description),
new XElement("Attributes", i.Attributes),
new XElement("Quantity", i.Quantity),
new XElement("UnitPrice", i.UnitPrice),
new XElement("InkColor", i.InkColor)))
);
xmlDoc.Save(Server.MapPath(#"~/Xml/Orders.xml"));
RedirectToAction("Save");
}
I wrote an extension for same purpose. I think much easier . you can just use as orders.EntityToXml();
public static class XmlExtensions
{
public static bool EntityToXml<T>(this T entity, string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
var dir = Path.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(dir))
{
throw new ArgumentNullException(nameof(filePath));
}
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var serializer= new System.Xml.Serialization.XmlSerializer(typeof(T));
using (var stream = new StreamWriter(filePath))
{
serializer.Serialize(stream , entity);
return true;
}
}
}
I am creating a xml schema using schema object model, on step "set.compile()", I get the above mentioned error. I guess its related to the base type name of simpletype elements, help!
Is there any method, we can actually see what is giong in while set.compile() method compiles the code??
XmlSchemaSimpleType namesimpletype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction res = new XmlSchemaSimpleTypeRestriction();
res.BaseTypeName = new XmlQualifiedName("string","");
XmlSchemaMinLengthFacet facet1 = new XmlSchemaMinLengthFacet();
facet1.Value = "3";
XmlSchemaMaxLengthFacet facet2 = new XmlSchemaMaxLengthFacet();
facet2.Value = "10";
res.Facets.Add(facet1);
res.Facets.Add(facet2);
namesimpletype.Content = res;
XmlSchemaSimpleType phonetype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction phone_res = new XmlSchemaSimpleTypeRestriction();
phone_res.BaseTypeName = new XmlQualifiedName("string", "");
XmlSchemaMinLengthFacet phone_facet1 = new XmlSchemaMinLengthFacet();
phone_facet1.Value = "4";
XmlSchemaMaxLengthFacet phone_facet2 = new XmlSchemaMaxLengthFacet();
phone_facet2.Value = "20";
phone_res.Facets.Add(phone_facet1);
phone_res.Facets.Add(phone_facet2);
phonetype.Content = phone_res;
XmlSchemaSimpleType notetype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction note_res = new XmlSchemaSimpleTypeRestriction();
note_res.BaseTypeName = new XmlQualifiedName("string", "");
XmlSchemaMinLengthFacet note_facet1 = new XmlSchemaMinLengthFacet();
note_facet1.Value = "0";
XmlSchemaMaxLengthFacet note_facet2 = new XmlSchemaMaxLengthFacet();
facet2.Value = "50";
note_res.Facets.Add(note_facet1);
note_res.Facets.Add(note_facet2);
notetype.Content = note_res;
XmlSchemaComplexType employeetype = new XmlSchemaComplexType();
XmlSchemaSequence emp_seq = new XmlSchemaSequence();
XmlSchemaElement firstname = new XmlSchemaElement();
firstname.Name = "firstname";
firstname.SchemaType = namesimpletype;
XmlSchemaElement lastname = new XmlSchemaElement();
lastname.Name = "lastname";
lastname.SchemaType = namesimpletype;
XmlSchemaElement homephone = new XmlSchemaElement();
homephone.Name = "homePhone";
homephone.SchemaType = phonetype;
XmlSchemaElement notes = new XmlSchemaElement();
notes.Name = "notes";
notes.SchemaType = notetype;
emp_seq.Items.Add(firstname);
emp_seq.Items.Add(lastname);
emp_seq.Items.Add(homephone);
emp_seq.Items.Add(notes);
employeetype.Particle = emp_seq;
/* XmlSchemaAttribute employeeid = new XmlSchemaAttribute();
employeeid.Name = "employeeid";
employeeid.SchemaTypeName = new XmlQualifiedName("int", "");
employeeid.Use = XmlSchemaUse.Required;
employeetype.Attributes.Add(employeeid);
*/
XmlSchemaComplexType complextype = new XmlSchemaComplexType();
complextype.Name = "employees";
XmlSchemaElement employee = new XmlSchemaElement();
employee.Name = "employee";
employee.SchemaType = employeetype;
employee.MinOccurs = 0;
employee.MaxOccursString = "unbounded";
XmlSchemaSequence emps_seq = new XmlSchemaSequence();
emps_seq.Items.Add(employee);
complextype.Particle = emps_seq;
XmlSchema schema = new XmlSchema();
schema.Items.Add(complextype);
XmlSchemaSet set = new XmlSchemaSet();
set.Add(schema);
set.Compile();
/* try
{
set.Compile();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
} */
FileStream stream = new FileStream(textBox1.Text, FileMode.Open);
XmlTextWriter writer = new XmlTextWriter(stream, null);
schema.Write(writer);
writer.Close();
Try to use full name with namespace:
res.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
See Example section on page http://msdn.microsoft.com/en-us/library/1c4sky9s(v=vs.110).aspx
My goal: To create a windows form application (executable) through the use of CodeDom. By this I mean I would like a form (with some code behind the form) and turn it into an executable file (as if I had gone into Visual Studio and clicked "Build" > "Build File"). Admittingly, I found this example online and I have since lightly modified it. I am getting errors while trying to generate this code - errors that I have never seen before. Furthermore, I could not find these errors on Google (odd right?)...
Here is the error I am getting:
Element type System.CodeDom.CodeExpression is not supported.
Parameter name: e
I am getting this error on the following line:
CodeProvider.GenerateCodeFromCompileUnit(Unit, writer, new CodeGeneratorOptions());
Here is my full code:
{
CodeDomProvider CodeProvider = CodeDomProvider.CreateProvider("CSharp");
// Create the Unit
CodeCompileUnit Unit = new CodeCompileUnit();
// Define a namespace and add Imports statements
CodeNamespace Namespaces = new CodeNamespace("Test.CreateForm");
Namespaces.Imports.Add(new CodeNamespaceImport("System"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Drawing"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Xml"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Data"));
Unit.Namespaces.Add(Namespaces);
// Declare the type including base type
CodeTypeDeclaration MyType = new CodeTypeDeclaration("Form1");
MyType.IsClass = true;
MyType.TypeAttributes = System.Reflection.TypeAttributes.Public;
MyType.BaseTypes.Add("System.Windows.Forms.Form");
Namespaces.Types.Add(MyType);
// Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();
Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),"InitializeComponent", new CodeExpression() {}));
Constructor.Attributes = MemberAttributes.Public ;
MyType.Members.Add(Constructor);
// Declare component container
MyType.Members.Add(new CodeMemberField("System.ComponentModel.IContainer", "components"));
// Implement the Dispose method
CodeMemberMethod DisposeMethod = new CodeMemberMethod();
DisposeMethod.Name = "Dispose";
DisposeMethod.Attributes = MemberAttributes.Family;
DisposeMethod.Parameters.Add(
new CodeParameterDeclarationExpression(
typeof(Boolean), "disposing"));
CodeConditionStatement Statement = new CodeConditionStatement();
Statement.Condition = new CodeArgumentReferenceExpression("disposing");
CodeConditionStatement TrueStatement = new CodeConditionStatement();
TrueStatement.Condition =
new CodeBinaryOperatorExpression(
new CodeArgumentReferenceExpression("components"),
CodeBinaryOperatorType.IdentityInequality,
new CodePrimitiveExpression(null));
TrueStatement.TrueStatements.Add(
new CodeMethodInvokeExpression(
new CodeFieldReferenceExpression(null,
"components"), "Dispose", new CodeExpression() {}));
Statement.TrueStatements.Add(TrueStatement);
DisposeMethod.Statements.Add(Statement);
DisposeMethod.Statements.Add(new CodeMethodInvokeExpression( new CodeBaseReferenceExpression(), "Dispose", new CodeArgumentReferenceExpression[]
{new CodeArgumentReferenceExpression("disposing")}));
MyType.Members.Add(DisposeMethod);
// InitializeComponent
CodeMemberMethod InitializeMethod = new CodeMemberMethod();
InitializeMethod.Name = "InitializeComponent";
InitializeMethod.Attributes = MemberAttributes.Private;
InitializeMethod.CustomAttributes.Add(
new CodeAttributeDeclaration(
"System.Diagnostics.DebuggerStepThrough"));
InitializeMethod.Statements.Add(
new CodeAssignStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "components"),
new CodeObjectCreateExpression(
new CodeTypeReference(
typeof(System.ComponentModel.Container)),
new CodeExpression() { })));
MyType.Members.Add(InitializeMethod);
// Main entry point
CodeEntryPointMethod MainMethod = new CodeEntryPointMethod();
MainMethod.Name = "Main";
MyType.Members.Add(MainMethod);
//Add mouse move event
CodeMemberEvent eventstate = new CodeMemberEvent();
eventstate.Name = "MouseMove";
eventstate.Attributes = MemberAttributes.Final | MemberAttributes.Public;
eventstate.Type = new CodeTypeReference("System.Windows.Forms.MouseEventHandler");
MyType.Members.Add(eventstate);
string OutputName = "Some.cs";
try
{
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BlankLinesBetweenMembers = true;
options.ElseOnClosing = false;
options.BracingStyle = "C";
// This is what we'll write the generated code to
IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(OutputName, false), " ");
try
{
CodeProvider.GenerateCodeFromCompileUnit(Unit, writer, new CodeGeneratorOptions());
writer.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
writer.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// Create the compiler options
// Include referenced assemblies
CompilerParameters Options = new CompilerParameters();
Options.GenerateExecutable = true;
Options.OutputAssembly = "TestForm1.exe";
Options.CompilerOptions = "/target:winexe";
Options.MainClass = "Test.CreateForm.Form1";
string[] referenceAssemblies = { "System.dll", "System.Data.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.XML.dll" };
Options.ReferencedAssemblies.AddRange(referenceAssemblies);
//Build and look for compiler errors
CompilerResults Result = CodeProvider.CompileAssemblyFromFile(Options, "Some.cs");
if (Result.Errors.Count > 0)
{
foreach(CompilerError ce in Result.Errors)
{
Console.WriteLine(ce.ErrorText);
}
}
else
{
Console.WriteLine("compiled successfully");
}
Console.WriteLine("press enter to continue");
Console.ReadLine();
}
You have many instances where you create an empty CodeExpression, such as in the constructor code:
// Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();
Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(), "InitializeComponent", new CodeExpression() { }));
If you don't want to pass any parameters to the method (which is the case in the code above), simply don't pass anything (CodeMethodInvokeExpression constructor takes a params[] array, so if you don't pass anything, it means that it receives an empty array):
// Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();
Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),
"InitializeComponent"));
in case above code is not spitting the required code make sure you are closed the IndentedTextWriter e.g. writer.Close() enjoy..
CodeMemberMethod DisposeMethod = new CodeMemberMethod();
DisposeMethod.Name = "Dispose";
DisposeMethod.ReturnType = new CodeTypeReference(typeof(void));
DisposeMethod.Attributes = MemberAttributes.Override | MemberAttributes.Private;
DisposeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "disposing"));
myDesignerClass.Members.Add(DisposeMethod);
CodeConditionStatement cstif2 = new CodeConditionStatement();
CodeExpression dis = new CodeVariableReferenceExpression("disposing");
CodeExpression comp = new CodeVariableReferenceExpression("components");
cstif2.Condition = new CodeBinaryOperatorExpression(dis, CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(dis, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)));
CodeExpression dispos = new CodeMethodInvokeExpression(comp, "Dispose", new CodeExpression[] { });
cstif2.TrueStatements.Add(dispos);
DisposeMethod.Statements.Add(cstif2);
CodeExpression bdispos = new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Dispose", new CodeExpression[] { });
DisposeMethod.Statements.Add(bdispos);
Replace () after CodeExpression with [] and error will vanish.
I've this generic list
List<zil> listKD = new List<zil>
{
new zil{day="Mon",c="1",S1="08:00",S2="08:40",S3="08:47"},
new zil{day="Mon",c="2",S1="08:50",S2="09:30",S3="09:37"},
new zil{day="Mon",c="3",S1="09:40",S2="10:20",S3="10:27"},
new zil{day="Mon",c="4",S1="10:30",S2="11:10",S3="11:17"},
new zil{day="Tue",c="1",S1="08:00",S2="08:40",S3="08:47"},
new zil{day="Tue",c="2",S1="08:50",S2="09:30",S3="09:37"},
new zil{day="Wed",c="1",S1="08:00",S2="08:40",S3="08:47"},
new zil{day="Wed",c="2",S1="08:50",S2="09:30",S3="09:37"},
new zil{day="Thu",c="1",S1="08:00",S2="08:40",S3="08:47"},
new zil{day="Thu",c="2",S1="08:50",S2="09:30",S3="09:37"},
new zil{day="Thu",c="3",S1="09:40",S2="10:20",S3="10:27"},
new zil{day="Fri",c="1",S1="08:00",S2="08:40",S3="08:47"},
new zil{day="Fri",c="2",S1="08:50",S2="09:30",S3="09:37"},
new zil{day="Fri",c="3",S1="09:40",S2="10:20",S3="10:27"},
new zil{day="Fri",c="4",S1="10:30",S2="11:10",S3="11:17"},
};
and I want save,this list xml but I can't like this xml file
alt text http://aliaydin.com.tr/exXml.jpg
this code doesn't work for I want
XElement zXml = new XElement("Days",
from g in listKD
select new XElement("Day",
new XAttribute("id", g.Day),
new XElement("clock",
new XAttribute("id", g.c),
new XElement("s1", g.s1),
new XElement("s2", g.s2),
new XElement("s3", g.s3)
)));
ZXml.Save("abc.xml");
Thanks...
I think you haven't grouped by day; perhaps something like:
var el = new XElement("Days",
from z in listKD
group z by z.day into tmp
select new XElement("Day",
new XAttribute("id", tmp.Key),
from item in tmp
select new XElement("clock",
new XAttribute("id", item.c),
new XElement("s1", item.S1),
new XElement("s2", item.S2),
new XElement("s3", item.S3))
));
string s = el.ToString(); // or save etc
Update re comment; to reverse it, something like:
XElement parsed = XElement.Parse(s);
var newList = (from day in parsed.Elements("Day")
from clock in day.Elements("clock")
select new zil
{
day = (string)day.Attribute("id"),
c = (string)clock.Attribute("id"),
S1 = (string)clock.Element("S1"),
S2 = (string)clock.Element("S2"),
S3 = (string)clock.Element("S3")
}).ToList();
To filter to a specific day:
from day in parsed.Elements("Day")
where (string)day.Attribute("id") == "Mon"
from clock in day.Elements("clock")
...
[XmlArray("Zils"), XmlArrayItem("Zil", typeof(zil))]
public List<zil> listKD = new List<zil>();