简体   繁体   中英

Parsing XML File To Strings in C#

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.

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

Your DataBase node has no value, only attributes such as Driver, Server, ...

To retrieve attribute value:

 string driver = xmlNode.SelectSingleNode("database").Attributes["Name"] ;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM