I wrote a c# class that generate a html file and return this a string.
But I need to add a preview this document HTML (it can be in the browser), and print out option this document.
My code:
public class Class1
{
public string HTMGenerator()
{
string html = "<p>test</p>";
var xDocument = new XDocument(
new XDocumentType("html", null, null, null),
new XElement("html",
new XElement("head"),
new XElement("body"
XElement.Parse(html)),
)
);
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true,
IndentChars = "\t"
};
using (var sw = new StringWriter())
{
using (var writer = XmlWriter.Create(sw, settings))
{
xDocument.WriteTo(writer);
}
return sw.ToString();
}
}
}
Try this:
string filename = "Your FileName.html";
File.WriteAllText(filename, HTMGenerator());
Process.Start(filename);
Here's how I would write your code:
void Main()
{
var filename ="Your File.html";
var instance = new Class1();
var document = instance.HTMGenerator();
document.Save(filename);
Process.Start(filename);
}
public class Class1
{
public XDocument HTMGenerator()
{
string html = "<p>test</p>";
var xDocument =
new XDocument(
new XDocumentType("html", null, null, null),
new XElement(
"html",
new XElement("head"),
new XElement(
"body",
XElement.Parse(html))));
return xDocument;
}
}
Related
Hello and sorry if question is strange and sorry for bad english.
My code:
xws.OmitXmlDeclaration = true;
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
string lb = "\r\n";
XElement I11 = new XElement("I11", lb,
new XElement("I11_TIPAS", "2"), lb,
new XElement("I11_PAV", "pav"), lb,
new XElement("I11_KODAS_IS", "985"), lb,
from iseip in eip
select new XElement("I12", lb,
new XElement("DI12_BAR_KODAS", iseip.DI12_BAR_KODAS), lb,
new XElement("I12_KODAS_SS", iseip.I12_KODAS_SS), lb,
new XElement("I12_KIEKIS", iseip.I12_KIEKIS), lb,
new XElement("I12_FRAKCIJA", iseip.I12_FRAKCIJA), lb), lb
);
I11.Save(xw);
}
System.IO.File.WriteAllText("bbb.eip", sb.ToString());
Output:
Need get like this:
Problem every I12 node must be in new line. Where is problem?
Try following :
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Indent = true;
List<EIP> eip = new List<EIP>();
using (XmlWriter xw = XmlWriter.Create("bbb.eip", xws))
{
XElement I11 = new XElement("I11", new object[] {
new XElement("I11_TIPAS", "2"),
new XElement("I11_PAV", "pav"),
new XElement("I11_KODAS_IS", "985")
});
foreach(var iseip in eip)
{
XElement I12 = new XElement("I12", new object[] {
new XElement("DI12_BAR_KODAS", iseip.DI12_BAR_KODAS),
new XElement("I12_KODAS_SS", iseip.I12_KODAS_SS),
new XElement("I12_KIEKIS", iseip.I12_KIEKIS),
new XElement("I12_FRAKCIJA", iseip.I12_FRAKCIJA)
});
I11.Add(I12);
}
I11.Save(xw);
}
}
public class EIP
{
public string DI12_BAR_KODAS { get;set;}
public string I12_KODAS_SS { get;set;}
public string I12_KIEKIS { get;set;}
public string I12_FRAKCIJA { get;set;}
}
Try the following.
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(sb.ToString());
xmlDocument.Save(#"D:\\Code2Try\bbb.eip");
XMLDocument saves in proper format.
I am trying to convert Netsuite Record(CashSale) into XML equivalent using XMLSerializer in c# application. However properties with datatype double not reflected in XML string
I have created a class in c# with double datatype property , I can see the property and value in xml string
I have tried converting Netsuite Cashsale class to xml string. Double datatype properties are not reflected in the xml string
CashSale cs = new CashSale();
cs.altHandlingCost = Convert.ToDouble(10.73.ToString(), CultureInfo.CurrentCulture);
cs.entity = new RecordRef { internalId = "311", type = RecordType.customer };
cs.externalId = "54658";
cs.memo = "POS Memo";
cs.tranDate = DateTime.Now.AddDays(-1);
cs.undepFunds = false;
cs.account = new RecordRef { internalId = "915" };
cs.subsidiary = new RecordRef { internalId = "2" };
cs.location = new RecordRef { internalId = "101" };
CashSaleItem[] item = { new CashSaleItem { amount = 10,taxAmount=1, taxCode = new RecordRef { internalId = "7" }, description = "dec", item = new RecordRef { externalId = "4000Bev" } } };
cs.itemList = new CashSaleItemList { item = item };
var a=Serialize(cs);
WriteResponse writeRes = Client.Service.upsert(cs);
public static string Serialize(object dataToSerialize)
{
if (dataToSerialize == null) return null;
using (StringWriter stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(dataToSerialize.GetType());
serializer.Serialize(stringwriter, dataToSerialize);
return stringwriter.ToString();
}
}
Expected: For Netsuite class, all properties including double datatype should be converted into XML string
Actual: Properties with datatype Double are not converted into XML
Minimum Reprocable Steps:
Create a Web Reference using https://webservices.netsuite.com/wsdl/v2019_1_0/netsuite.wsdl
Create a object for CashSale
Assign some values for double datatype fields alongwith others.
Serialise to XML string
This may help you out:
public string ToXML()
{
using(var stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(stringwriter, this);
return stringwriter.ToString();
}
}
public static YourClass LoadFromXMLString(string xmlText)
{
using(var stringReader = new System.IO.StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(YourClass ));
return serializer.Deserialize(stringReader) as YourClass ;
}
}
I have found solution for this issue:
Changes Done: I have added one more boolean field amountspecified in request and set it to true
I have this methods in my License Class as shown below.
public void CreateTestLincense(LicenseModel.CustomerLicense objData)
{
string data = CreateXML(objData);
File.WriteAllText(licensePath, data);
}
private string CreateXML(Object YourClassObject)
{
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(YourClassObject.GetType());
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, YourClassObject);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
return xmlDoc.InnerXml;
}
}
But I'm trying to save the xml after passing its properties.
CustomerLicense custLic = new CustomerLicense();
custLic.CustomerId = 1;
custLic.Names = "David Okwudili";
custLic.Email = "michealdavid910#yahoo.com";
custLic.Phone = "09089786756";
custLic.ExpiringDate = DateTime.Now;
custLic.Serial = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
//Create XML Documant
MAH.Tools.Licensing.License lic = new MAH.Tools.Licensing.License(true);
lic.CreateTestLincense(custLic);
But it has been throwing an exception 'There was an error reflecting type' from XmlSerializer xmlSerializer = new XmlSerializer(YourClassObject.GetType());.
Please i need help, Thanks.
When I run <!-- This list contains names/words with specific casing - and specific to english only --> will be removed in new destination.
Is there any way to prevent it from happening. I event tried with XDocument.Root same thing happened.
Ps: I know method are not inside class :).
<!-- This list contains names/words with specific casing - and specific to english only -->
<ignore_list>
<name>A.M.</name>
<name>Aaron</name>
<name>Abbie</name>
<name>Abi</name>
<name>Abigail</name>
<name>Abolfazl</name>
<name>Adam</name>
</ignore_list>
private static void EnGBNamesEtc()
{
var listNames = new List<string>(){"some", "names");
var xele = XElement.Load(#"C:\Users\ivandro\Source\subtitleedit\Dictionaries\en_GB_names_etc.xml");
var names = listNames.Except(xele.Elements("name").Select(n => n.Value)).ToList();
foreach (var newName in names)
{
xele.Add(new XElement("name", newName));
}
SaveToNewXml(xele, #"D:\Backup\en_GB_names_etc1.xml");
}
private static void SaveToNewXml(XElement xelem, string dest)
{
XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
var ordered = xelem.Elements("name").OrderBy(element => element.Value).ToList();
using (XmlWriter xw = XmlWriter.Create(dest, xws))
{
xelem.ReplaceAll(ordered);
xelem.Save(xw);
}
}
That's possibly because you're using XElement which only capable of representing single node (when you have two "root" nodes, <ignore_list> and the comment node). Use XDocument instead of XElement to keep the comment node, for example (I tried to keep minimal changes to your original code) :
private static async void EnGBNamesEtc()
{
var listNames = new List<string>(){"some", "names");
var xdoc = XDocument.Load(#"C:\Users\ivandro\Source\subtitleedit\Dictionaries\en_GB_names_etc.xml");
var names = listNames.Except(xdoc.Root.Elements("name").Select(n => n.Value)).ToList();
foreach (var newName in names)
{
xdoc.Root.Add(new XElement("name", newName));
}
SaveToNewXml(xdoc, #"D:\Backup\en_GB_names_etc1.xml");
}
private static void SaveToNewXml(XDocument xdoc, string dest)
{
XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
var ordered = xdoc.Root.Elements("name").OrderBy(element => element.Value).ToList();
using (XmlWriter xw = XmlWriter.Create(dest, xws))
{
xdoc.Root.ReplaceAll(ordered);
xdoc.Save(xw);
}
}
i have one xml string like this
string stxml="<Status>Success</Status>";
I also creaated one xml document
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode rootNode = doc.CreateElement("StatusList");
doc.AppendChild(rootNode);
i need an output like this.
<StatusList>
<Status>Success</Status>
</StatusList>
How can i achieve this.if we using innerhtml,it will insert.But i want to insert xml string as a xmlnode itself
A very simple way to achieve what you are after is to use the often overlooked XmlDocumentFragment class:
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode rootNode = doc.CreateElement("StatusList");
doc.AppendChild(rootNode);
//Create a document fragment and load the xml into it
XmlDocumentFragment fragment = doc.CreateDocumentFragment();
fragment.InnerXml = stxml;
rootNode.AppendChild(fragment);
Using Linq to XML:
string stxml = "<Status>Success</Status>";
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("StatusList", XElement.Parse(stxml)));
You could instead use the XElement class:
string stxml = "<Status>Success</Status>";
var status = XElement.Parse(stxml);
var statusList = new XElement("StatusList", status);
var output = statusList.ToString(); // looks as you'd like
If you want to write the new statusList content to a file:
statusList.Save(#"C:\yourFile.xml", SaveOptions.None);
you ca try it using xmlwriter
using (XmlWriter writer = XmlWriter.Create("new.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("StatusList");
writer.WriteElementString("Status", "Success"); // <-- These are new
writer.WriteEndDocument();
}
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using System.ComponentModel;
public class MyClass
{
public static void RunSnippet()
{
XmlNode node = default(XmlNode);
if(node == null)
Console.WriteLine(bool.TrueString);
if(node != null)
Console.WriteLine(bool.FalseString);
XmlDocument doc = new XmlDocument();
node = doc.CreateNode (XmlNodeType.Element,"Query", string.Empty);
node.InnerXml=#"<Where><Eq><FieldRef Name=""{0}"" /><Value Type=""{1}"">{2}</Value></Eq></Where>";
string xmlData = ToXml<XmlNode>(node);
Console.WriteLine(xmlData);
XmlNode node1 = ConvertFromString(typeof(XmlNode), #"<Query><Where><Eq><FieldRef Name=""{0}"" /><Value Type=""{1}"">{2}</Value></Eq></Where></Query>") as XmlNode;
if(node1 == null)
Console.WriteLine(bool.FalseString);
if(node1 != null)
Console.WriteLine(bool.TrueString);
string xmlData1 = ToXml<XmlNode>(node1);
Console.WriteLine(xmlData1);
}
public static string ToXml<T>(T t)
{
string Ret = string.Empty;
XmlSerializer s = new XmlSerializer(typeof(T));
using (StringWriter Output = new StringWriter(new System.Text.StringBuilder()))
{
s.Serialize(Output, t);
Ret = Output.ToString();
}
return Ret;
}
public static object ConvertFromString(Type t, string sourceValue)
{
object convertedVal = null;
Type parameterType = t;
if (parameterType == null) parameterType = typeof(string);
try
{
// Type t = Type.GetType(sourceType, true);
TypeConverter converter = TypeDescriptor.GetConverter(parameterType);
if (converter != null && converter.CanConvertFrom(typeof(string)))
{
convertedVal = converter.ConvertFromString(sourceValue);
}
else
{
convertedVal = FromXml(sourceValue, parameterType);
}
}
catch { }
return convertedVal;
}
public static object FromXml(string Xml, Type t)
{
object obj;
XmlSerializer ser = new XmlSerializer(t);
using (StringReader stringReader = new StringReader(Xml))
{
using (System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stringReader))
{
obj = ser.Deserialize(xmlReader);
}
}
return obj;
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
From my experience it is always better to work with unique id's i suggest u look in that situation first and then come back to this page, and research/position my code for a try if u did not yet have a solution for it.
I just finished it on my side for my own project, i have modified abit to look more integrated for your project.
Good luck. Sorry for the late response ;-)
XmlDocument xDoc = new XmlDocument();
string Bingo = "Identification code";
xDoc.Load(pathFile);
XmlNodeList idList = xDoc.GetElementsByTagName("id");
XmlNodeList statusList = xDoc.GetElementsByTagName("Status");
for (int i = 0; i < idList.Count; i++)
{
StatusNode = "<Status>fail</Status>";
XmlDocumentFragment fragment = xDoc.CreateDocumentFragment();
fragment.InnerXml = StatusNode;
statusList[i].InnerXml = "";
statusList[i].AppendChild(fragment);
if (statusList[i].InnerText == Bingo)
{
StatusNode = "<Status>Succes!</Status>";
fragment.InnerXml = Status;
statusList[i].InnerXml = "";
statusList[i].AppendChild(fragment);
}
}
xDoc.Save(pathFile);