Loading XML file from UNC Path not working propertly - c#

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

Related

XML Edit to file using 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.

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.

Long paths bug in Windows?

I have the following file:
C:\Users\Jan\Documents\Visual Studio 2010\Projects\AzureTests\Build\82df3c44-0482-47a7-a5d8-9b39a79cf359.cskpg\WebRole1_778722b2-eb95-476d-af6a-917f269a0814.cssx\39e5cb39-cd18-4e1a-9c25-72bd1ad41b49.csman
I can open this file fine via the open window in notepad++, or via the explorer. However, opening via the Run window doesn't work. It gives an 'cannot find the file' dialog. When I query the filesystem in C# with:
var dir = new DirectoryInfo(#"C:\Users\Jan\...")
var fil = dir.GetFiles("*.csman")[0];
The file is also in the list of returned files but I can't do a:
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(fil.FullName);
Because this fails with an 'incorrect data at (1,1)' error. Because the XmlDocument thinks the file is empty. However a File.ReadAllBytes on this file succeeds. This works:
var buf = File.ReadAllBytes(fil.FullName);
using (var ms = new MemoryStream())
{
ms.Write(buf, 0, (int) buf.Length);
ms.Seek(0, SeekOrigin.Begin);
xmlDoc.Load(ms);
}
The problem doesn't occur when calling...
xmlDoc.Save(fil.FullName);
Can someone explain what is happening here?
XmlDocument.LoadXml expects a string that directly contains the XML data.
Parameters
xml
Type: System.String
String containing the XML document to load.
It is therefore interpreting the path-string as if it were XML (which will obviously be invalid, which is why the exception is thrown).
Use the XmlDocument.Load method instead.
Parameters
filename
Type: System.String
URL for the file containing the XML document to load. The URL can be either a local file or an HTTP URL (a Web address).
You don't face the problem when calling XmlDocument.Save, because, like Load, it's single parameter represents the path to the file.
Basically, the somewhat long file-path you've got there is a red-herring and not the root-cause of the issue you are facing.
And your other problem:
Windows "Run" requires quotes around the path name if there are spaces in it.

Invalid Assembly XML File

I am trying to read the XML Documentation file (C#) using this ocde -
Type classType = typeof(Point);
string documentationFileLocation = classType.Assembly.CodeBase;
if ( !string.IsNullOrEmpty(documentationFileLocation) && documentationFileLocation.StartsWith("file:///") )
{
documentationFileLocation = documentationFileLocation.Replace(".exe",".xml");
documentationFileLocation = documentationFileLocation.Replace("file:///","");
if(File.Exists(documentationFileLocation))
{
XElement document = XElement.Load(documentationFileLocation);
// Some Code Logic Here using LINQ
}
else
{
Console.WriteLine("Please Go to Project Properties->Build and check 'XML Documentation file'");
I have a LINQ Query after XElement document = XElement.Load(sr) which dosen`t work,
So I put a breakpoint in the LINQ Query and I am getting this error -
XmlException - Data at the root level is invalid. Line 1, position 1.
How I can fix it?
Edit:Changed the code a little - just deleted StreamReader
Well, it sounds like it simply isn't a valid XML file.
If you print out the result of sr.ReadToEnd() instead of calling XElement.Load, what does it look like? If you try to load the file into an XML editor, what happens?
Btw, it's better to use a using statement than calling Dispose explicitly: with your current code, the StreamReader isn't disposed if Load throws an exception.
Finally, is there any reason you're not just using XElement.Load(documentationFileLocation)?
Have you tried XDocument.Load() instead of using XElement? If the file begins with an XML declaration <?xml ..., you might get this error when trying to load an element from it.
Edit: the file you pasted on pastebin has no encoding specified. Can you try to open this file in notepad and re-save it as ANSI, the see if it loads? Just to make sure that we don't have an encoding or BOM problem.

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