I have searched for solution for this but all I found are questions how to prevent this.
I have a simple code for saving and loading XML.
XDocument xDoc;
public Form1()
{
InitializeComponent();
xDoc = new XDocument(new XElement("root", new XElement("data")));
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string input = textBox1.Text;
xDoc.Root.SetElementValue("data", input);
rtxtXPreview.Text = xDoc.ToString();
txtValuePreview.Text = xDoc.Root.Element("data").Value;
}
private void button1_Click(object sender, EventArgs e)
{
SaveAndLoad();
}
private void SaveAndLoad()
{
string dataNodeValue;
xDoc.Save(path);
dataNodeValue = xDoc.Descendants("data").First().Value;
txtValuePreview.Text = dataNodeValue;
rtxtXPreview.Text = xDoc.ToString();
}
textBox1: is the input for the data element.
rtxtXPreview: is a rich textbox for displaying the text of the XML.
txtValuePreview: is a textbox for displaying the element value.
The problem is that when I enter value like:
A
B
C
The XML shows fine with the line breaks but once I hit the button the document is saved without those. So when I debugged my code I found that the characters \n\r is replaced with \n so I searched for this problem and found this code:
private void SaveAndLoadFixed()
{
string dataNodeValue;
XmlWriterSettings xmlWriterSettings =
new XmlWriterSettings { NewLineHandling = NewLineHandling.None, Indent = true };
using (XmlWriter xmlWriter = XmlWriter.Create(path, xmlWriterSettings))
{
xDoc.Save(xmlWriter);
xmlWriter.Flush();
}
//xDoc.Save(path);
XElement xDatabaseElement;
using (XmlTextReader xmlTextReader = new XmlTextReader(path) { WhitespaceHandling = WhitespaceHandling.Significant })
{
xmlTextReader.MoveToContent();
xDatabaseElement = XElement.Load(xmlTextReader);
}
dataNodeValue = xDatabaseElement.Descendants("data").First().Value;
txtValuePreview.Text = dataNodeValue;
rtxtXPreview.Text = xDatabaseElement.ToString();
}
This worked fine but why the characters \n\r not replaced with  because when I tried to type the character < or > it was replaced with < & > respectively ?
Related
I am attempting to create an interface that allows me to select 3 XSLT files and merge them together to then be transformed using an XML. I have a working transformation code I am creating a user interface for.
Transformation code:
public static void Transform(string sXmlPath, string sXslPathBody, string sXslPathHead, string sXslPathFoot, string sXslPathMerged)
{
try
{
XNamespace ns = "http://www.w3.org/1999/XSL/Transform";
//load Xml
XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
//Load Body
XElement xslt = XElement.Load(sXslPathBody);
//Add Code To Body
xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", sXslPathFoot)));
xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", sXslPathHead)));
XElement body = xslt.Descendants("body").Single();
body.AddFirst(new XElement(ns + "call-template", new XAttribute("name", "Header")));
body.Add(new XElement(ns + "call-template", new XAttribute("name", "Footer")));
//Save Combined File
//XElement.Save("c:\temp.xlst");
xslt.Save(sXslPathMerged);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
//load Combined File
myXslTrans.Load(sXslPathMerged);
//Merge XML with Combined File
XmlTextWriter myWriter = new XmlTextWriter ("result.html", null);
//transform Xml
myXslTrans.Transform(myXPathDoc, null, myWriter);
myWriter.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
}
}
The Transformation code works fine however I am trying to set each stage to a button which will allow me to select any 3 XSLT files I wish, as well as any XML I wish. Then a button to merge the 3 XSLT files together & create a HTML output.
Code:
public partial class Form1 : Form
{
String HeadFileSelected, BodyFileSelected, FootFileSelected, XmlFileSelected, MergeFiles;
public Form1()
{
InitializeComponent();
}
//Head
private void openFileHead_FileOk(object sender, CancelEventArgs e)
{
}
private void header_Click(object sender, System.EventArgs e)
{
if (openFileHead.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
HeadFileSelected = openFileHead.FileName;
string filename = HeadFileSelected;
textBox2.Text = HeadFileSelected;
}
}
//Body
private void openFileBody_FileOk(object sender, CancelEventArgs e)
{
}
private void body_Click(object sender, System.EventArgs e)
{
if (openFileBody.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
BodyFileSelected = openFileBody.FileName;
string filename = BodyFileSelected;
textBox3.Text = BodyFileSelected;
}
}
//Foot
private void openFileFooter_FileOk(object sender, CancelEventArgs e)
{
}
private void footer_Click(object sender, System.EventArgs e)
{
if (openFileFooter.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FootFileSelected = openFileFooter.FileName;
string filename = FootFileSelected;
textBox4.Text = FootFileSelected;
}
}
//Xml
private void openFileXml_FileOk(object sender, CancelEventArgs e)
{
}
private void xml_Click(object sender, System.EventArgs e)
{
if (openFileXml.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
XmlFileSelected = openFileXml.FileName;
}
}
//Merge
private void openFileMerge_FileOk(object sender, CancelEventArgs e)
{
}
private void merge_Click(object sender, EventArgs e)
{
//XmlTransformUtil objXMLTrans = new XmlTransformUtil();
XmlTransformUtil.Transform(XmlFileSelected, BodyFileSelected, HeadFileSelected, FootFileSelected, MergeFiles);
}
}
I have managed to get the XML selection & the 3 XSLT selections to work fine it's just the Merge button that is not working as I cannot attribute the String MergeFiles; to Transform(string sXslPathMerged)
I understand why it does not work but I don't now the solution that will give me the result I need.
Managed to figure it out, I needed to define MergeFiles as the saved XSLT which wasn't going anywhere because it was null. Did it by adding the following in my form.
MergeFiles = "C:\\Users\\user\\Desktop\\TEMP.xslt";
using (StreamReader sr = new StreamReader (Convert.ToString(adsClient.ReadAny(hActVel, typeof(double)))))
using (StreamWriter sw = new StreamWriter(NameYourFile.Text + DateTime.Today.ToString("MM_dd_yyyy") + ".csv"))
{
if (sr == null)
return;
string line;
while ((line = sr.ReadLine()) != null)
{
string[] columns = line.Split(',');
sw.WriteLine(hActVel);
}
}
and also i want an answer for how to write Text box data(i.e double) which is changing every second to ( .c s v) file? in c# windows form..
I am using this app in My project to create Front end for the servo motor .
I already tried this question in
http://area51.stackexchange.com
but i dint get any answer....please help me..
To create a file with the name as textbox:
string path = #"D:\"+NameYourFile.Text+".csv";
File.Create(path).Dispose();
OR you want to write text to it:
string text = textbox.text; // your textbox
// WriteAllText creates a file, writes the specified string to the file,
// and then closes the file.
System.IO.File.WriteAllText(path, text);
Writing textbox to CSV file:
//string filePath = #"C:\test.csv";
string delimiter = ",";
string outputtofile = textbox.text;
int length = outputfile.length;
StringBuilder sb = new StringBuilder();
for (int index = 0; index < length; index++)
sb.AppendLine(string.Join(delimiter, output[index]));
File.WriteAllText(path, sb.ToString());
if you have text like this in textbox Abcdefg
then it will right to file like:
A,b,c,d,e,f,g
Let's assume you have 2 TextBoxes ValueTextBox and FileNameTextBox. If the value in the ValueTextBox is changing automatically you can register the TextChaned event and append text to the file as follows:
private void ValueTextBox_TextChanged(object sender, EventArgs e)
{
StreamWriter writer = File.AppendText(FileNameTextBox.Text);
writer.WriteLine(ValueTextBox.Text);
writer.Close();
}
Or you can use a Timer control that will fire every second to read the value from the ValueTextBox and append it to the file.
private void timer1_Tick(object sender, EventArgs e)
{
StreamWriter writer = File.AppendText(FileNameTextBox.Text);
writer.WriteLine(String.Format("{0},{1},{2}", DateTime.Now.ToString("hh:mm:ss"), BigMotorTextBox.Text, SmallMotorTextBox.Text));
writer.Close();
}
Based on your last comment:
In form load, create the file and write the header to it, as follows:
private void Form2_Load(object sender, EventArgs e)
{
StreamWriter writer = new StreamWriter("Path_Of_The_File", false);
writer.WriteLine(String.Format("{0},{1},{2}", "\"Time\"", "\"Big motor Actual Velocity\"", "\"Small Motor Actual Velocity\""));
writer.close();
}
In the Timer tick event, write only the values as follows:
private void timer1_Tick(object sender, EventArgs e)
{
StreamWriter writer = File.AppendText(FileNameTextBox.Text);
writer.WriteLine(String.Format("{0},{1},{2}", DateTime.Now.ToString("hh:mm:ss"), BigMotorTextBox.Text, SmallMotorTextBox.Text));
writer.Close();
}
finally my code becomes like this..
private void WriteToCSV_Click(object sender, EventArgs e)
{
string path = NameYourFile.Text + "_" + DateTime.Now.ToString("MM_dd_yyyy") + ".csv";
if (!System.IO.File.Exists(path))
{
// Create file if no Exists
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(string.Format("{0},{1},{2}", "\"Time\"", "\"Big Motor Actual Velocity\"", "\"Small Motor Actual Velocity\""));
}
}
this.timer2.Start();
}
private void CreateCSVFile_Click(object sender, EventArgs e)
{
this.timer2.Stop();
MessageBox.Show("File is Created");
}
private void timer2_Tick(object sender, EventArgs e)
{
string dt = DateTime.Now.ToString("hh.mm.ss.ffffff");
string var1 = (dt);
string var2 = adsClient.ReadAny(hActVel, typeof(double)).ToString(); ;
string var3 = adsClient.ReadAny(hSActVel, typeof(double)).ToString(); ;
StreamWriter sw = File.AppendText(NameYourFile.Text + "_" + DateTime.Today.ToString("MM_dd_yyyy") + ".csv");
{
if (BigMotorActualVelocity.Checked && SmallMotorActualVelocity.Checked)
{
sw.WriteLine(string.Format("{0},{1},{2}",var1, var2, var3));
}
else if (BigMotorActualVelocity.Checked)
{
sw.WriteLine(string.Format("{0},{1}",var1 , var2));
}
else if (SmallMotorActualVelocity.Checked)
{
sw.WriteLine(string.Format("{0},{1},{2}",var1," ",var3));
}
else
{
sw.WriteLine(string.Format("{0}",var1));
}
sw.Dispose();
}
I'm having trouble coming up with the correct code to download pictures from a RSS feed and then handing that download off to RadControls slide View or Pagination.
The only thing I can get with the code I'm using is either the text for the pictures or just thumbnails of the pictures, not the full image. I must be missing something or leaving something out.
This is for Windows Phone C#
The web links for the RSS feeds are generic for testing purposes.
//Constructor
public MainPage()
{
InitializeComponent();
}
private void FlickrSearch_Click(object sender, RoutedEventArgs e)
{
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler
(webclient_DownloadStringCompleted);
}
void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("error");
}
// parsing Flickr
XElement XmlTweet = XElement.Parse(e.Result);
XNamespace ns = "http://api.flickr.com/services/feeds/photos_public.gne?tag="; // flilckr
listBox1.ItemsSource =
from tweet in XmlTweet.Descendants("item")
select new FlickrData
{
ImageSource = tweet.Element(ns + "thumbnail").Attribute("url").Value,
Message = tweet.Element("description").Value,
UserName = tweet.Element("title").Value,
PubDate = DateTime.Parse(tweet.Element("pubDate").Value)
};
}
I have found the way you are parsing & fetching the inner data is erroneous. I have closely verified the XML data from Flickr and modified the logic accordingly.
Here goes the complete code:
void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("error");
}
// parsing Flickr
XElement XmlTweet = XElement.Parse(e.Result);
string ns = "http://www.w3.org/2005/Atom";
XName entry = XName.Get("entry", ns);
XName loc = XName.Get("loc", ns);
XName title = XName.Get("title", ns);
XName published = XName.Get("published", ns);
XName link = XName.Get("link", ns);
XName content = XName.Get("content", ns);
XName url = XName.Get("url", ns);
listBox1.ItemsSource =
from tweet in XmlTweet.Elements(entry)
select new FlickrData
{
ImageSource = tweet.Element(link).Attribute("href").Value,
Message = tweet.Element(content).Value,
UserName = tweet.Element(title).Value,
PubDate = DateTime.Parse(tweet.Element(published).Value)
};
}
In windows forms, I have some labels in the panel and I would like to display the static values from the listBox1 where it loads collection of (.rtdl) files from a folder.
When user selects each then I want to display the corresponding attribute values to the labels in the panel.
Code to populate listBox1:
private void Form1_Load(object sender, EventArgs e)
{
PopulateListBox(listBox1, #"C:\TestLoadFiles\", "*.rtdl");
}
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file);
}
}
Code to read files from the listBox1:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
FileInfo file = (FileInfo)listBox1.SelectedItem;
DisplayFile(file.FullName);
string path = (string)listBox1.SelectedItem;
DisplayFile(path);
}
private void DisplayFile(string path)
{
string xmldoc = File.ReadAllText(path);
using (XmlReader reader = XmlReader.Create(xmldoc))
{
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "description":
if (!string.IsNullOrEmpty(reader.Value))
label5.Text = reader.Value; // your label name
break;
case "sourceId":
if (!string.IsNullOrEmpty(reader.Value))
label6.Text = reader.Value; // your label name
break;
// ... continue for each label
}
}
}
}
When I select the file, it's throwing this error illegal characters in path at using (XmlReader reader = XmlReader.Create(xmldoc)).
Please tell me what is wrong here???
XmlReader.Create(string) takes a path as input (or a stream), not the actual text string - see here: http://msdn.microsoft.com/en-us/library/w8k674bf.aspx.
So just remove this line:
string xmldoc = File.ReadAllText(path);
And in DisplayFile change this:
using (XmlReader reader = XmlReader.Create(xmldoc))
To this:
using (XmlReader reader = XmlReader.Create(path))
That said, you're doing things in a very difficult way. LINQ to XML is way simpler for what you're trying to achieve.
Try this in DisplayFile instead:
private void DisplayFile(string path)
{
var doc = XDocument.Load(path);
var ns = doc.Root.GetDefaultNamespace();
var conn = doc.Root.Element(ns + "connection");
label5.Text = conn.Element(ns + "description").Value;
label6.Text = conn.Element(ns + "sourceId").Value;
// and so on
}
When i run my program and click on the second tab multiple times it creates labels x amount of times and im unsure if theirs a way to sort of only read the xml only once... I tried using a .close method but that did not work for me... any help would be appreciated thank you
private void tabPage2_Enter(object sender, EventArgs e)
{
if (tabControl1.SelectedTab == tabPage2)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("xmldoc.xml");
foreach (XmlNode node in xmlDoc.SelectNodes("check/tick/mark"))
{
Label l = new Label();
System.Drawing.Point l1 = new System.Drawing.Point(65, 48 + a);
l.Location = l1;
l.Text = node.SelectSingleNode("score").InnerText;
tabPage2.Controls.Add(l);
a += 25;
}
}
}
Do the xml reading in a different function. Create a variable to store whether or not you have already read the xml. Only invoke the xml reading function if it has not already been called.
This happens beacuse your code read multiple-times the same xmldocument so try:
bool read = false;
void ReadXmDocument()
{
using(XmlDocument xmlDoc = new XmlDocument())
{
xmlDoc.Load("xmldoc.xml");
foreach (XmlNode node in xmlDoc.SelectNodes("check/tick/mark"))
{
Label l = new Label();
System.Drawing.Point l1 = new System.Drawing.Point(65, 48 + a);
l.Location = l1;
l.Text = node.SelectSingleNode("score").InnerText;
tabPage2.Controls.Add(l);
a += 25;
}
read = true;
}
}
private void tabPage2_Enter(object sender, EventArgs e)
{
if(tabControl1.SelectedTab == tabPage2 && read == false) ReadXmlDocument();
}