How to get attribute value using SelectSingleNode?

后端 未结 3 1143
野的像风
野的像风 2021-01-11 09:19

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

相关标签:
3条回答
  • 2021-01-11 09:58

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-11 10:01

    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.

    0 讨论(0)
  • 2021-01-11 10:23

    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
    
    0 讨论(0)
提交回复
热议问题