XML Edit to file using C# - c#

I am working on a WPF application and I have a simple XML file that I am parsing using 'XmlDocument' and is working fine for the readinh part.
I want the use to be able to add, edit or delete any node and save these changes to the file.
I tried using 'XElement' but it seems to change the instance itself and not the file.
My XML file looks something like this:
<Configuration>
<A_0.04_5>
<ML407Configuration>
<AM_Amp>10</AM_Amp>
<AMRJ_Amp>10</AMRJ_Amp>
<FM_Freq>20</FM_Freq>
<FM_Phase_Shift>20</FM_Phase_Shift>
</ML407Configuration>
<BertConfiguration>
<BERT_LR>25.78125</BERT_LR>
<BERT_PRBS>7</BERT_PRBS>
<BERT_Scaling>1000</BERT_Scaling>
</BertConfiguration>
</A_0.04_5>
<B_1.333_0.15>
<ML407Configuration>
<AM_Amp>10</AM_Amp>
<AMRJ_Amp>10</AMRJ_Amp>
<FM_Freq>20</FM_Freq>
<FM_Phase_Shift>20</FM_Phase_Shift>
</ML407Configuration>
<BertConfiguration>
<BERT_LR>25.78125</BERT_LR>
<BERT_PRBS>7</BERT_PRBS>
</BertConfiguration>
</B_1.333_0.15>
<C_4_0.05>
<ML407Configuration>
<BUJ_LR>25</BUJ_LR>
<BUJ_Pattern>7</BUJ_Pattern>
<PM_BUJ_Amp>7</PM_BUJ_Amp>
<BUJ_Amp>80</BUJ_Amp>
</ML407Configuration>
<BertConfiguration>
<BERT_LR>25.78125</BERT_LR>
<BERT_PRBS>7</BERT_PRBS>
</BertConfiguration>
</C_4_0.05>
</Configuration>
What I tried is the following:
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/Configuration.xml";
XElement xml = XElement.Load(filePath);
// This seems to remove the node from xml instance and not from the file
// Should I save the file again or is there another way to do it
// Same applies for add and edit
xml.Elements("C_4_0.05").Remove();
I have seen a lot of similar questions but I don't know if any of them change directly to the file or not

XElement.Load loads an XML structure from a file into memory. Any changes you make to that structure are also done in memory. If you want to write those changes back to a file (technically called serialization) you need to call XElement.Save.

Related

XML file keeps being overwritten

So I'm currently working on an ASP.NET project. It requires me to write a List<> onto a XML file. I created a "data.xml" file within the project folder and here are my few lines of code:
XmlSerializer serializer = new XmlSerializer(typeof(List<BookItem>));
TextWriter filestream = new StreamWriter("data.xml");
serializer.Serialize(filestream, book);
filestream.Close();
it works well
like this
until I want to add a new record, then the file is overwritten every single time. I believe i only need few tricky lines of code to solve this problem but since my research didn't bring up any answer, i really need your help.

C# Webservice response xml displaying as pdf

I am new to C# web development. I am developing a software that receives response from webservice in XML format. (includes barcodes generated by webservice).
There is an option given by webservice provider, that i have to add a line
(Example<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">)
as a second line in the xml and display in web browser by using style sheets provided by webservice provider. If i have to choose this option, how can i add that line as second line in the received xml file also how can i map the style sheets provided by the webserive in the project for this xml.
If i dont take that option, Is it possible to display the data in xml as a pdf(includes barcodes generated by webservice), if i dont choose the option .
If I understand your question correctly, you want to:
Add a stylesheet specification to an existing XML
Convert an XML to PDF
1. ADDING A STYLESHEET
There is an option given by webservice provider, that i have to add a line [...] as a second line in the xml and display in web browser by using style sheets
This is done using e.g. Linq, like in this answer.
First of all, I think the example you used, i.e.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
may be inaccurate, as it is the first line of a XSL file (a stylesheet); those kind of files are used to transform an XML into another file (a different XML or an HTML, like in your case). However, you say
using style sheets provided by webservice provider
so my guess is that you already have those stylesheets and you can you use them, rather than creating them yourself.
If so, the line you want to add is like
<?xml-stylesheet type="text/xsl" href="helloWorld.xsl"?>
Let's suppose you already have your XML stored into an XDocument variable named "Document" with its root element being "Root"
var FilePath = "Example.xml";
var Document = XDocument.Load(FilePath);
var Root = XDocument.Descendants("Root").Single();
Then you can add your stylesheet this way, getting a new XML:
var NewDocument = new XDocument(
new XProcessingInstruction("xml-stylesheet", "type='text/xsl'ref='helloWorld.xsl'"),
Root);
2. XML to PDF
There are several ways to do this.
You might parse your XML, retrieve the elements you want to show on your PDF, use a library like iTextSharp to create a specific layout and place their contents on the file.
Or, since you already have an XML and you can transform it to an HTML using an XSL, you can use wkHtmlToPdf.
Let me know if you need more details.

Loading XML file from UNC Path not working propertly

I want to load an XML file located on my server so I can get the value of the XML Element called "CheckInterval" and store it on a string called "NewIntervalSet".
I am loading the following XML file called "ConfigFile.xml".
<?xml version="1.0" encoding="utf-8"?>
<Cart>
<CartConfiguration>
<CheckInterval>0.25</CheckInterval>
</CartConfiguration>
</Cart>
The way that I am loading it is the following:
XElement xelement;
xelement = XElement.Load(Path.Combine("\\\\server\\public\\Engineering","ConfigFile.xml"));
The way that I'm storing the XML element "CheckInterval" into the string "NewIntervalSet" is the following:
string NewIntervalSet;
NewIntervalSet=xelement.Descendants("CartConfiguration")
.Select(x => x.Element("CheckInterval").Value).FirstOrDefault();
When I place a breakpoint where the file is being loaded I can see that the file is loading correctly, so I know the path is right, but when it tries to select the XML element it skips this line of code and it returns a null value, therefore a null string on the "NewIntervalSet" variable. I have no idea why is doing this, when I use the same code but the path is on the local machine it works correct.
Your program may be running into a permissions issue. According to MSDN, XElement creates by calling XmlReader.Create, which in turn has the following to say
A default XmlUrlResolver with no credentials is used to access any
external resources such as a document type definition (DTD), entities,
schemas, and so on. If the external resource is located on a network
resource that requires authentication, specify an XmlResolver with the
necessary credentials using the XmlReaderSettings.XmlResolver
property.
Since your XML document is located on a network path, it's using default/null credentials, causing it to get no read permissions and an empty document. Try opening the file as a stream so you can make a run where it reads out text, and then pipe that stream into a new XElement using this overload. Alternatively, instantiate the XmlResolver yourself so you can set the credentials.
I fix this problem by loading the XML file as an XDocument and not as an XElement. The new way that I'm loading the XML file is the following:
XDocument xDocument;
xDocument= XDocument.Load(Path.Combine("\\\\server\\public\\Engineering","ConfigFile.xml"));

XML header missing after converting an XML file into a Binary Format File

I have a problem. I have an XML spreadsheet file that I'm trying to send via email. So I converted into a binary file and attached it to an email. The problem is when I'm trying to open it (on Excel), it's not showing the data that I saved. When I opened it like an XML file I realized that it didn't saved the XML header:
The way it should be:
<?xml version="1.0" encoding="utf-8"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
...
<Styles>
...
</Styles>
<Worksheet>
...
</Worksheet></Workbook>
after converting:
<Worksheet>
...
</Worksheet>
I've tried to use an xmldocument but i wasn't working, I also tried using a string, still not working. This is how I convert the XML to binary:
UTF8Encoding encoding = new UTF8Encoding();
binaryFile = encoding.GetBytes(xmlFile);
How can I fix this problem?
Thanks.
I think we need more information on how you're converting the XML file.
From your description it sounds like you've saved an Excel Spreadsheet to XML and for whatever reason you cannot just attach this text document to an email. My guess is you're using a method to attach the XML file that requires a byte array and can't just be provided a file location. If you could provide more information on this, it would help us figure out where things are going wrong for you.
The part I'm really stuck on is:
I've tried to use an xmldocument but i wasn't working, I also tried
using a string, still not working.
How did you try string? Did you read the file from disk using FileStream? If so, you should have been able to retrieve the full contents of the file.
Were you using XmlDocument the whole time and trying XmlDocument.OuterXml? This probably won't give you the control headers since they're not part of the XML body inside the root node.
So really there are two things I would have tried. First, if I had an XML file on disk and needed to attach it to an email through code and my only option was to provide a byte array, I'd do something like:
using (FileStream fs = new FileStream("", FileMode.Open, FileAccess.Read))
{
byte[] binaryFile = new byte[fs.Length];
fs.Read(binaryFile, 0, buff.LongLength);
//Copy the byte array to your email object.
}
Now if this isn't what you're doing, you'll need to provide a lot more detail on what you are starting with (file on disk?), what you need to do (send automated email?), what constraints you have and any other information that would limit potential solutions.
I've found my mistake: I didn't serialized the XML file so that's why after the conversion it just shows the data without the XML header. so there's 2 ways to resolve this problem:
first, we can concatenate the header with the data string, or we can use the serialize function. This is where I've found how to do it.

Loading a custom section from XML

I want to add an ability to an application that I'm developing for accessing configuration.
The application will search by default in the app.config file for a section that I give it.
If it was not found in the app.config, it will look for it in the DB, in a specific table that has the following columns:
SectionType, SectionName, SectionData
The SectionData column is a text column, that contains the data of the section in XML format (exactly like it should be in the app.config file)
I can take the SectionData content, but I can't load it into the custom ConfigurationSection, like I would have done if it was in the app.config file:
var mySectionObj = ConfigurationManager.GetSection("myCustomSection");
To simplify, my question is actually how can I get the custom ConfigurationSection object from a XML string instead of a configuration file?
You could load the string into an XDocument object and read it from there.
I don't think that's possible at all - with the ConfigurationManager class from .NET, it is as far as I know not even possible to open whatever file you want - you are restricted to the app.config file. Reading configuration data from another source than a file? No can do.
You can either analyse the XML-String yourself (with "XmlDocument.LoadXml(string)") or you modify the app.config file and read it again.
The question would be: Why wouldn't there be the CustomSection in the config file? Should this be considered an error (then updating the config file would be best, I think). Or is it intended, that some config files don't have the CustomSection?
If the settings may be in the XML-File, adding the setting to the file would be like this:
XmlDocument appconfig = new XmlDocument();
appconfig.Load("[config_filename]");
XmlNode root = appconfig.DocumentElement;
XmlDocument mysection = new XmlDocument();
mysection.LoadXml([SectionData]);
XmlNode customSection = mysection.DocumentElement;
XmlNode tempNode = appconfig.ImportNode(customSection, true);
root.AppendChild(tempNode);
appconfig.Save("[config_filename]");
...
var mySectionObj = ConfigurationManager.GetSection("myCustomSection");
if this is not desirable, I see two possibilities:
First:
Do it nevertheless: Change the .config file, read it, and then change it back.
(or copy the file, change the original, read it, delete it, rename the copy back to the original name).
This way is not nice, it's somehow impure, in my opinion, but it has some great advantages: It works and it is easy to maintain.
Second:
Load your XML string into a XmlDocument: XmlDocument.LoadXml(xmlstring)
Then analyse the xmldocument, with "doc.ChildNodes" or "doc.SelectNodes(xpath)" or "doc.SelectSingleNode(xpath)".
This will be much more work, especially since you will have to maintain to routines to get the configuration settings into your project, so I would not recommend this method. Strongly not recommend.

Categories

Resources