David Green
David Green

Reputation: 1234

Reading <property> tag

I was asked today to look at a new project - reading in some XML and doing some analysis. I know a little C#. I have gotten this far with this code that so far works. I get the 4 node lists successfully. I have a couple problems. First I am not sure how to access what is in the tag on any of the nodes in any of the lists. Second, I'd prefer to be able to use LINQ queries but XmlNodeList doesn't seem to support that syntax. In the sample XML below, I'd like to be able to get all the vdisks that belong to a particular IO Group or mdisk as determined by io_group_name or mdisk_grp_name property. Most of what I looked at gave examples for accessing the [Attribute] list and searches all used properties/atttributes interchanged.

What I tried is also below, it gave a null value exception. The Attributes list only has one attribute. I can't find any examples to do what I want and it isn't clear from inspecting the node in the debugger what I need to access to do what I want.

//this works

XmlTextReader reader = new XmlTextReader(_InputFile);
XmlDocument doc = new XmlDocument();
doc.Load(reader);

XmlNodeList clusterlist = doc.SelectNodes("//object[@type='cluster']");
XmlNodeList controllerlist = doc.SelectNodes("//object[@type='controller']");
XmlNodeList mdisklist = doc.SelectNodes("//object[@type='mdisk']");
XmlNodeList vdisklist = doc.SelectNodes("//object[@type='vdisk']");


// this did not work - got null value exception
foreach (XmlNode vdisknode in vdisklist)
{
    string str = vdisknode.Attributes["mdisk_grp_name"].Value;
}

A sample of the XML:

<object type="vdisk">
     <property name="id" value="0" />
     <property name="name" value="nim01_vd06_gmt" />
     <property name="IO_group_id" value="0" />
     <property name="IO_group_name" value="ossvc06_iogrp0" />
     <property name="status" value="online" />
     <property name="mdisk_grp_id" value="0" />
     <property name="mdisk_grp_name" value="T1_OSIBM06_MDG1" />
     <property name="capacity" value="644245094400" />
     <property name="type" value="striped" />
</object>

Upvotes: 3

Views: 466

Answers (1)

abatishchev
abatishchev

Reputation: 100308

object node has only one attribute: type

string type = vdiskNode.Attributes["type"].Value;

property node has two attributes: name and value:

string name = propertyNode.Attributes["name"].Value;
string value = propertyNode.Attributes["value"].Value;

What you need I deem is to extend the XPath query:

"//object[@type='vdisk']/property[@name='mdisk_grp_name']/@value"

Or use LINQ to XML:

from obj in doc.Load(xml).Root.Elements("object")
where (string)obj.Attribute("type") == "vdisk"
from prop in obj.Elements("property")
//where (string)prop.Attribute("name") == name
select prop.Value

Upvotes: 1

Related Questions