I’m having trouble getting my program to read this XML file properly, it will need to write to it also but not yet. Just note that this is only a little bit of the code
XmlDocument InstalledList = new XmlDocument();
InstalledList.Load(AppsInstalledFileNamePath);
//Sets the PackageNode to the correct part of the XmlDocument
XmlNodeList PackagesNode = InstalledList.GetElementsByTagName("installed");
foreach (XmlNode InstalledListNodes in PackagesNode)
{
//If the title is the same as what the user typed, continue on
if (InstalledListNodes.Attributes["title"].InnerText.Equals(packagename) == true)
{
BatchProcessFileName = InstalledListNodes.Attributes["uninstallername"].InnerText;
Console.WriteLine("Filename OK");
I also took the try statement out so I wouldn’t have to add the catch
Below is the XML File that it is trying to read (and later write)
<?xml version="1.0" encoding="utf-8" ?>
<packages>
<installed>
<sampleapp title="sampleapp" id="00001" uninstallername="sampleapp.bat" installdate="11/15/09"></sampleapp>
<sampleapp2 title="sampleapp2" id="00002" uninstallername="sampleapp2.bat" installdate="11/16/09"></sampleapp2>
</installed>
<uninstalled>
</uninstalled>
</packages>
The code runs, but it has a NullReference Exception at
InstalledListNodes.Attributes["title"].InnerText.Equals(packagename) == true
FYI and contrary to popular believe:
InnerTextis nevernullfor attributes or elements. That means, that you don’t have to check forInnerTextbeing null at all. Empty elements and attributes have an empty string forInnerText:However, the attribute itself can return
nullif it doesn’t exist. And it is useless, as was already pointed out by jrista, to useInnerTextunless you really have to. Stick toValueinstead.Solving your issue
Many have already commented on that. You have:
with the XML you showed, this will never work, as
<installed>does not have attributes. Try:which will not (yet) give the effect you want, but
someNodenow points to a node that actually holds the title attribute, showing you how to get rid of this error.On to an easier solution: SelectNodes
After removing your error, I’d like to show you another way: XPath. This type of tasks is really much easier by using XPath. Here is my take at your problem (not tested):
Important note: what others have said about checking the return values of node steps is still very important. If anything of your input data is not there, your code will fail hard. Just always check every step, or use more XPath to make your life easier.
Update: the FYI
Update: added solution
Update: added alternative solution (couldn’t resist)