I am parsing a xml document, I need find out the gid (an attribute) value (3810).
Based on SelectSingleNode()
. I found it is not easy to find the attri
You can query XmlDocument
itself not DocumentRoot
:
XmlDocument doc = new XmlDocument();
XmlNode book = doc.SelectSingleNode("..");
if (book != null)
{
XmlAttribute gid = book.Attributes["gid"];
if (gid != null)
{
string value = gid.Value;
}
}
You can write
XmlAttribute gidAttribute = (XmlAttribute)book.Attributes.GetNamedItem("gid");
String gidValue = null;
if (gidAttribute!=null)
value = gidAttribute.Value;
Alternatively, expand the Xpath to fetch the attribute, e.g.
Attributes[AttrDir[@name='EFEM']/AttrDir[@name='Aligner']/AttrDir[@name='SequenceID']/AttrObj[@text='Slot01']]/@gid
If the @gid is unique, then you can simply use the Xpath
"//AttrObj[@gid='3810']"
To fetch the desired node with the given id. But note that each request will search through the entire document. It will be more efficient to fetch all the nodes, and then put them in a map, keyed by id.
"//AttrObj[@gid]"
Use XmlNode.SelectNodes
to fetch a list of all AttrObj with a @gid attribute.
The problem here was they your XPath was all wrong. You had this:
Attributes[AttrDir[@name='EFEM']/AttrDir[@name='Aligner']/AttrDir[@name='SequenceID']/AttrObj[@text='Slot01']]
which would either select or not select the Attributes element depending on whether all the names matched up. This XPath should take you directly to the gid attribute you want:
Attributes/AttrDir[@name='EFEM']/AttrDir[@name='Aligner']/AttrDir[@name='SequenceID']/AttrObj[@text='Slot01']/@gid