Invalid Assembly XML File - c#

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.

Related

XmlException: Text node cannot appear in this state. Line 1, position 1

Before I get into the issue, I'm aware there is another question that sounds exactly the same as mine. However, I've tried that solution (using Notepad++ to encode the xml file as UTF-8 (without BOM) ) and it doesn't work.
XmlDocument namesDoc = new XmlDocument();
XmlDocument factionsDoc = new XmlDocument();
namesDoc.LoadXml(Application.persistentDataPath + "/names.xml");
factionsDoc.LoadXml(Application.persistentDataPath + "/factions.xml");
Above is the code I have problems with. I'm not sure what the problem is.
<?xml version="1.0" encoding="UTF-8"?>
<factions>
<major id="0">
...
Above is a section of the XML file (the start of it - names.xml is also the same except it has no 'id' attribute). The file(s) are both encoded in UTF-8 - in the latest notepad++ version, there is no option of "encode in UTF-8 without BOM" afaik UTF-8 is the same as UTF-8 without BOM.
Does anyone have any idea what the cause may be? Or am I doing something wrong/forgetting something? :/
You are receiving an error because the .LoadXml() method expects a string argument that contains the XML data, not the location of an XML file. If you want to load an XML file then you need to use the .Load() method, not the .LoadXml() method.

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

ReadXml from a Resource - Explanation

I've been working on a project (C#) and part of it was filling a data grid with an embedded xml file.
Although I've now found a way to make this work, i am still confused as to to theory behind it. And I'd like to stop and make sure i fully understand it before i continue with this project.
The code that i have working currently is;
XmlDataDocument myXML = new XmlDataDocument();
StringReader mytempXML = (new StringReader(BasicTest.Properties.Resources.myxml));
myXML.DataSet.ReadXml(mytempXML);
What is confusing to me is that before this solution, I was trying the below;
myXML.DataSet.ReadXml(BasicTest.Properties.Resources.myxml);
and it wasn't working. However using the full file path (like below) was working.
myXML.DataSet.ReadXml("C:/..etc../myxml.xml");
The Question I have is: why is a StringReader required for the ReadXml method if you're reading from a resource, but using a full file path works without?
If anyone could provide an explanation, that would be great.
Thanks.
This is because the ReadXml method takes a string. That string must be the name of a file. It cannot be XML. If you pass it a string that is XML, it will think that is the name of the file! It doesn't have the smarts to look at the string and ask "Is this string XML, or is it a file name?" and figure that out.
// Summary:
// Reads XML schema and data into the System.Data.DataSet using the specified
// file.
//
// Parameters:
// fileName:
// The filename (including the path) from which to read.
public XmlReadMode ReadXml(string fileName);
By wrapping the XML in a stringreader or a stream or something, you are calling a different overload, that expects XML instead of a file name.

XmlSerializer Deserialize fails in release mode

This is pretty odd. I have a configuration file which is well formed XML. I create a stream from the file and serialize it using what seems to be pretty typical code:
TextWriter tw = new StreamWriter(tempFile);
I use a serializer created as follows:
XmlSerializer ConfigSettingSerializer = new XmlSerializer(typeof(ConfigSettings));
Where ConfigSettings is just a container class containing string variables and values.
I then take the serialized stream and stash it away as a configuration using the ConfigurationManager class and AppSettings. I then retrieve the serialized data from appSettings and attempt to convert the stream back to the original class:
string configXml = ConfigurationManager.AppSettings[Id];
using (StringReader reader = new StringReader(configXml))
{
retVal = (ConfigSettings)MVHelper.ConfigSettingSerializer.Deserialize(reader);
}
This all works perfectly well until I switch from Debug to Release, when I get an error on the Deserialize call about invalid XML, complaining about the very last character in the document: There is an error in XML document (92, 18). The inner exception is: "Data at the root level is invalid. Line 92, position 18". The document is identical to the one generated in debug mode, and it renders fine in any browser. My guess is that there maybe something else going on and that the real error is somehow being masked, but so far I don't see it. Any advice would be greatly appreciated.
Thanks,
Gary
Load the XML file in a hex editor or other binary editor and check for unprintable characters like an encoding preamble.

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.

Categories

Resources