Reputation: 1597
I'm writing a program and I'm trying to grab information from an XML file, break it up and store the information in 4-5 different strings. Here's the code I have to grab the XML file.
private void getVersionXML()
{
sVersionConfigPath = sLocationKey + "Core\\config.xml"; //Path to XML File
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sVersionConfigPath); //Load config.xml
XmlNodeList xmlNodes = xmlDoc.GetElementsByTagName("PrimaryDatabase");
foreach (XmlNode xmlNode in xmlNodes)
{
label1.Text = xmlNode.SelectSingleNode("database").InnerText; //Breaks Here
}
}
Here is what the XML file looks like.
<ProgXML>
<PrimaryDatabase Updating="N">
<Database Driver="SQL Server" Server="serverName" User="sa" Password="Iyp4kvRIS7Orl+NjkhIjvg==" Database="dbName" Owner="" Port="" UncBase="" ImpUser="" />
<DataExists Action="Reset" When="5/20/2015 3:17:36 PM" />
<TableCollection Name="Core" Who="CPUser" ProcessID="0" ProcessName="" Status="Complete" When="5/20/2015 3:17:47 PM" LayoutVersion="39" DataVersion="39" />
<TableCollection Name="Prog" Who="CPUser" ProcessID="0" ProcessName="" Status="Complete" When="5/20/2015 3:17:47 PM" LayoutVersion="38" DataVersion="38" />
</PrimaryDatabase>
</ProgXML>
Essentially I'm just trying to get everything that shows in the <Database />
tag and store it into a string (or in this case, just print to a label for debugging purposes).
However the code breaks where I commented above with a NullReferenceException
for "Object reference not set to instance of an object". And I'm not quite sure where I went wrong. Any help would be greatly appreciated. Thanks.
Upvotes: 1
Views: 153
Reputation: 388
looks like it is a capitalization issue that's your specific problem: (it's "Database" in the Xml and "database" in C#.)
as previously mentioned, LINQ to Xml is also the way to go these days.
Also, consider using the "OuterXml" property instead if you just want a raw text representation of the element and all of its content.
Upvotes: 0
Reputation: 1718
Your DataBase node has no value, only attributes such as Driver, Server, ...
To retrieve attribute value:
string driver = xmlNode.SelectSingleNode("database").Attributes["Name"] ;
Upvotes: 1
Reputation: 15364
You can use Linq2Xml
var xDoc = XDocument.Load(filename);
var dict = xDoc.Descendants("Database")
.First()
.Attributes()
.ToDictionary(x => x.Name, x => x.Value);
If you want that values only for debugging purposes,
var str = string.Join("; ", xDoc.Descendants("Database")
.First()
.Attributes()
.Select(x => x.Name + "=" + x.Value));
Upvotes: 2