Reputation: 6969
I have a complex structure xml from which I need to read some element value. My xml is somewhat like this:
<plist version="1.0">
<dict>
<key>XYZ</key>
<dict>
<key>KEYVALUE1</key>
<dict>
<key>A</key>
<date>AVALUE1</date>
<key>B</key>
<string>BVALUE1</string>
</dict>
<key>KEYVALUE2</key>
<dict>
<key>A</key>
<date>AVALUE2</date>
<key>B</key>
<string>BVALUE2</string>
<key>C</key>
<string>CVALUE2</string>
</dict>
</dict>
</dict>
</plist>
What I need is: search for a dict with KEYVALUE2, and wherever I get it, pick BVALUE2 out of it (you can replace 2 with whatever number, I have just included 2 nodes for brevity).
I am newbie for xml programming and all my attempts to try out MS documentation have only confused me more. Sometimes I find a xmlreader example which didn't quite serve my purpose, and other time I got LINQ example which confused me because of its structure. Please help!
Upvotes: 1
Views: 5482
Reputation: 3416
There are many technologies that allow you to access XML.
Since linq wasn't your taste, you could do the following:
Use XmlDocument with XPath, such as in this example:
XmlDocument xmldoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string bvalue = xmlDoc.SelectSingleNode("//dict[key='" + key + "']/dict/string).InnerText;
But I would advice changing the structure of your XML first..
XML is a great relational data structure. The way your keys are arranged is not relational.. In my opinion, there should be one key on each level like this:
<dict>
<KeyValuePair>
<key type="date">A</key>
<value>AVALUE2</value>
</KeyValuePair>
<KeyValuePair>
<key type="string">B</key>
<value>BVALUE2</value>
</KeyValuePair>
</dict>
That way you could write:
string value = xmlDoc.SelectSingleNode("//KeyValuePair[key = 'B']/value").InnerText;
Good Luck!
Upvotes: 3