Get path from XML File using C# - c#

I'm needing to get a path say C:\SourceFiles\ from an XML File using C#.
I have been trying different escapes methods, but nothing seems to work correctly.
I have tried these:
#"C:\SourceFiles\ or C:\\SourceFiles\\ or "C:\\SourceFiles\\" and 'C:\SourceFiles'
None of these seem to work when reading from an XML file.
XmlDocument xDoc = new XmlDocument();
xDoc.Load(strpath);
string strsourceDirectory = xDoc.SelectSingleNode("Application/Setup/SourceDirectory").InnerText;
Here is the XML File:
<Application>
<Setup>
<SourceDirectory>"C:\SourceFiles\"</SourceDirectory>
<DestinationDirectory>#"C:\DestinationFiles\"</DestinationDirectory>
</Setup>
If someone has done this with C# and a XML file, please let me know how you did it.
Thanks,

Your XML file is invalid. You need to escape the backslash \\ and close the Application tag:
<Application>
<Setup>
<SourceDirectory>C:\\SourceFiles\\</SourceDirectory>
<DestinationDirectory>C:\\DestinationFiles\\</DestinationDirectory>
</Setup>
</Application>
With this valid XML, you will be able to get the path using your code:
string strsourceDirectory =
xDoc.SelectSingleNode("Application/Setup/SourceDirectory").InnerText;

Related

How can I ignore the namespace in an XML document in c#?

I'm trying to open a XML file in c#, find a node by attribute name, which is working fine and then displaying the name of an XML attribute in the same node.
My code is simple (as I pinched it from other sources!) and works on my test XML doc. However, when I try it with an actual file it doesn't work. I've been pulling my hair out (not that I have much left) and have discovered it's because of the xmlns attribute in the actual files I'm using. The path to the namespace does not exist.
My code is as follows:
XmlDocument doc = new XmlDocument();
doc.Load(#"c:\deroschedule\test.sym");
var orient = doc.SelectSingleNode("//Attr[#name='Orientation]/#value");
the above code works perfectly when xmlns is not included in the file. However, when xmlns is included the orient variable is null. The xmlns path doesn't exist, when i try to navigate to it in a browser I get a 404 error.
Not sure what a xml namespace is to be honest, but I have thousands of these files and can't manually edit them. Is there an easy way to get C# to overlook the namespace and just pretend it's not there? I've tried with Xpath, but that just blew my mind!
Ok I figured it out for myself. Thought I would post the answer here even though there are thousands of other answers apparently.
Where I went wrong was misunderstanding what the namespace actually does. Anyway I had to use xmlnamespacenmanager to declare the same namespace as in the xml file. Then I had to use the namespace in the query.
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\deroschedule\test6.sym");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("ma", "http://www.yournamespaceinfohere.com/");
var orient = doc.SelectSingleNode("//ma:attr[#name='Orientation']/#value", ns);
Now my next challenge is to try and read the bmp from the xml file, should be easy, right?!

Importing XML with 'µ' symbol into excel

I am trying to import an XML file into excel using Data -> Other Sources -> From XML Data import. When the file contains a 'µ' symbol, it gives the following error:
Invalid file reference. The path to the file is invalid, or one or
more of the referenced schemas could not be found.
The XML looks like this:
<root>
<File>
<FileName>Data\7.5 µg_mL Sample.pdf</FileName>
</File>
</root>
If i remove the microgram symbol, it works and Excel imports the data.
I am generating the XML file in .net using XNode.toString(), and if I run the XML through a validator, it returns no errors. It doesn't seem to matter if I put the XML declaration at the top of the file and declare it as UTF-8 or 16 either.
Any pointers welcome, i would ideally like to check for any characters that might cause this problem as i am guessing there are more than just the microgram symbol.
I am passing the XML string to a function that swaps out a custom xml file, i don't seem to have the option to change the file format here..
'Uses Ionic.Zip.ZipFile
Using zip As ZipFile = ZipFile.Read(fileDest)
zip.RemoveEntry(xmlPath)
zip.Save()
zip.AddEntry(xmlPath, customXml)
zip.Save()
End Using
Per the docs for the overload of AddEntry you are using:
The content for the entry is encoded using the default text encoding for the machine
You want this to be UTF-8, so you can use the overload that allows you to specify the encoding:
zip.AddEntry(xmlPath, customXml, Encoding.UTF8);

How to search through XML to find bad nodes

I have a large XML file (68Mb), I am using SQL Server Business Intelligence Studio 2008 to extract the XML data into a database. There is an error in the XML file some where that prevents it from executing. Possibly a missing tag or something like that. The file is so large I cant manually sort through it looking for the error.
Below is a sample of the the XML schema used.
How can I use XPath to sort through the XML in VS 2012 using C#?
An example would be great!
-<PhoneNumberList>
<PhoneNumber value="1234567890" type="Phone"/>
</PhoneNumberList>
-<YearsOfServiceList>
<YearsOfService experienceInMonths="24" description="SuperAdmin" objectCode="049"/>
</YearsOfServiceList>
</Person>
-<Person dob="1960-01-09T00:00:00" lastName="Smith" middleName="Will" firstName="John" id="9999-9999-9999">
-<SiteList>
-<Site id="2014" siteLongName="HA" siteCode="1255" systemCode="999">
-<StaffPositionList>
<StaffPosition id="73" staffPosition="Administrator"/>
</StaffPositionList>
</Site>
</SiteList>
-<ProgramList>
<Program id="1234" siteLongName="ABC" siteCode="0000" systemCode="205"/>
<Program id="5678" siteLongName="DEF" siteCode="0000" systemCode="357"/>
</ProgramList>
-<TypeList>
<Type Description="Leader" certificateType="D"/>
<Type Description="Professional" certificateType="P"/>
</TypeList>
-<EmailList>
<Email value="jsmith#somesite.com" type="Email"/>
</EmailList>
-<PhoneNumberList>
<PhoneNumber value="1234567890" type="Phone"/>
</PhoneNumberList>
-<YearsOfServiceList>
<YearsOfService experienceInMonths="24" description="SuperAdmin" objectCode="049"/>
</YearsOfServiceList>
</Person>
</PersonList>
</GetPersonDetail>
If you want to do it in code then create an XSD file describing a valid format for the data, embed it as a resource in your app and then use code like this
var errors = new List<string>();
var schemaSet = new XmlSchemaSet();
schemaSet.Add("", XmlReader.Create(new StringReader(Properties.Resources.NameOfXSDResource)));
document.Validate(schemaSet, (sender, args) =>
{
errors.Add(args.Message);
}
);
This will give you a list of validation errors.
You don't need to search "by hand" if you use a competent text editor. NotePad++'s XML plugin, for instance, can determine if your XML as a whole is well-formed or valid, and both instances will provide separate error messages.
If you don't have a schema and the file is well-formed, you can use the CLR's System.XML namespace to read in the document and then iterate through its nodes using LINQ-to-XML, which would allow you to very finely control which nodes go where. With LINQ, you could either create a new XML file with only the valid entries, procedurally correct the invalid entries as you determine where they are, or even just write to your SQL server database directly.
Your troubleshooting process should be something as follows:
Is the XML well-formed? I..e, does it comport to the fundamental rules of XML?
Is the XML valid? I.e., does it have the elements and attributes you expect?
Is your import query accurate?
For things like this I usually have luck checking and fixing the data in Notepad++. Install the XmlTools plugin and that has a menu for checking the xml syntax and tags.
Also, those dashes will give you problems, it's best to save out the xml file directly without copying by hand.
A 68MB XML file is no problem for XML editors such as XMLBlueprint 64-bit (http://www.xmlblueprint.com/) or Stylus Studio (http://www.stylusstudio.com/). Just check the well-formedness of your xml file (F7 in XMLBlueprint) and the editor will display the errors.

loading xml document error in c#

I'm trying to load a document with xml in c#
the name of xml file is variable, here is problem...
string filename="test01.xml";
XmlDocument root = new XmlDocument();
root.Load(filename);
the above code give me error: unable to connect to remote server or unable to load
but the following code works
XmlDocument root = new XmlDocument();
root.Load("test01.xml");
why is that?
You can try to specify the whole path (absolute path) to the file (not only the filename).
So instead of writing "test01.xml" you can try to write "C:\[... path to the file here]\test01.xml" and it should work as intended.
If you specify only the file name, the application will probably look for the file in the current directory (value in Environment.CurrentDirectory). I just tested this in a sample application.
It's worth mentioning that if you use FileName property from OpenFileDialog class as a case with 'using variable', it contains PATH to the file (despite its name ;)).
Does your XML contains DTD declaration with URL? Most probably parser tries to resolve it, and fails, because, say, automatic proxy does not accept its request.

Read in an XML String with Namespaces for Use in an XSL Transformation

In an ASP.NET 2.0 website, I have a string representing some well-formed XML. I am currently creating an XmlDocument object with it and running an XSL transformation for display in a Web form. Everything was operating fine until the XML input started to contain namespaces.
How can I read in this string and allow namespaces?
I've included the current code below. The string source comes from an HTML encoded node in a WordPress RSS feed.
XPathNavigator myNav= myPost.CreateNavigator();
XmlNamespaceManager myManager = new XmlNamespaceManager(myNav.NameTable);
myManager.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
string myPost = HttpUtility.HtmlDecode("<post>" +
myNav.SelectSingleNode("//item[1]/content:encoded", myManager).InnerXml +
"</post>");
XmlDocument myDocument = new XmlDocument();
myDocument.LoadXml(myPost.ToString());
The error is on the last line:
"System.Xml.XmlException: 'w' is an undeclared namespace. Line 12, position 201. at System.Xml.XmlTextReaderImpl.Throw(Exception e) ..."
Your code looks right.
The problem is probably in the xml document you're trying to load.
It must have elements with a "w" prefix, without having that prefix declared in the XML document
For example, you should have:
<test xmlns:w="http://...">
<w:elementInWNamespace />
</test>
(your document is probably missing the xmlns:w="http://")
Gut feel - one of the namespaces declared in //content:encoding is being dropped (probably because you're using the literal .InnerXml property)
What's 'w' namespace evaluate to in the myNav DOM? You'll want to add xmlns:w= to your post node. There will probably be others too.

Categories